Python 3 – for Loop Statements
Python is known for its readability and simplicity. One of the essential control structures used in Python is for loops. Loop statements are used to execute a block of code repeatedly. The for loop is one of the most commonly used loops in Python.
Syntax of For Loop in Python
The syntax of the for loop in Python is different from the syntax used in other programming languages. Here is the syntax used in Python:
for variable in sequence:
# Code to be executed
The for
keyword starts the loop, followed by a variable name to hold the values of the sequence element. The in
keyword is used to stipulate the sequence to iterate over. The code block inside the loop will be executed repeatedly until all values in the sequence have been processed.
Example of For Loop in Python
Let us take an example of how we can use the for loop in Python to iterate over a list of items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
In the example above, the for loop is used to loop through a list of fruits. The variable x
is assigned to each element in the list fruits. The code inside the loop then processes each value of x
.
For Loop Using Range Function
The range() function is used to generate a sequence of numbers to iterate over. Here is how we can use for loop and range() function together:
for i in range(3):
print(i)
Output:
0
1
2
In the example above, the for loop is used to iterate over numbers generated by the range() function. The method range(3)
produces 0
, 1
, and 2
.
Look for both key and value in dictionary
We can also use the for loop to iterate over a dictionary’s keys and values. Here’s an example:
fruits = {"apple": 5, "banana": 3, "cherry": 8}
for fruit, quantity in fruits.items():
print(fruit + " has " + str(quantity) + " pieces")
Output:
apple has 5 pieces
banana has 3 pieces
cherry has 8 pieces
In the above example, the fruits.items()
function returns a dictionary’s key-value pairs. The variable fruit
is assigned to each key in the dictionary, and the variable quantity
is assigned to each value in the dictionary.
Looping with Else
Python provides an additional feature to the loop structure with the else
statement. The else
statement is executed after the loop completes its usual iteration unless it’s been interrupted by a break statement.
for x in range(3):
print(x)
else:
print("Loop Completed!")
Output:
0
1
2
Loop Completed!
In the above example, the else
statement is executed after the for loop completes, printing “Loop Completed!”
Conclusion
Python’s for loop statement is used to iterate over a sequence of values. It allows code to execute multiple times without duplication, and the syntax used in a for loop statement is straightforward and easy to understand. It’s also possible to iterate over a dictionary, use range() to generate numbers, and add else statements when needed.