How to Write a For Loop in Python

04 May 2023 Balmiki Mandal 0 Python

Tutorial: How to Write a For Loop in Python

A loop is a programming construct that allows you to repeat a set of instructions until a certain condition is met. In Python, the for loop provides a way to iterate over an iterable object like lists, tuples, or dictionaries. This tutorial will cover how to write a for loop in Python.

What is a For Loop?

A for loop is a type of loop that allows you to iterate over an iterable object. This type of loop is known as a loop control structure, which means that it lets you control the number of times that a set of instructions can be repeated. A for loop will execute a set of instructions for each item in a given iterable object.

How to Write a For Loop in Python

Writing a for loop in Python is easy and straight forward. To begin, use the following syntax:

for item in iterable:
    # execute some code

The above syntax will loop through each item in the given iterable object (which can be a list, tuple or dictionary). For each item in the iterable, the code within the loop will be executed. You can then print out the item using the print() function.

For example:

arr = [1, 2, 3, 4, 5]

for item in arr:
    print(item) 

# Output
# 1
# 2
# 3
# 4
# 5

In the above example, we have defined a list called arr. We then wrote a for loop to loop through each item in the arr list and print it out. The result of the code will be 1 to 5 printed out on the screen.

You can also use for loops to loop through dictionaries. Dictionaries are key-value pairs, so when you loop through a dictionary, you can access both the key and the value at the same time. For example:

d = {'a':1, 'b':2, 'c':3, 'd':4}

for key, value in d.items():
    print(f"{key}: {value}")

# Output
# a: 1
# b: 2
# c: 3
# d: 4

The above example is using a ‘for each’ loop to loop through the dictionary d and print out each element. The .items() method is used to loop through the dictionary, and it returns both the key and value for each item in the dictionary. The result of this code will be the key and value pairs printed out on the screen.

Conclusion

In this tutorial, we covered how to write a for loop in Python. A for loop is a type of loop control structure that allows you to repeat a set of instructions for each item in an iterable object. We looked at how to write for loops for both lists and dictionaries. With for loops, you can easily loop through a given iterable object and perform a set of instructions for each item.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.