A for
loop in Python is used to repeat a block of code a specific number of times, or until a certain condition is met. It allows you to iterate over elements of a sequence (e.g. list, tuple, string, etc.) or other objects that support iteration. Discover the power of the Python for
loop and how it can simplify your code. Learn how to use the for
loop in Python to efficiently iterate over elements of a sequence or other objects. Get step-by-step examples and tips on how to make the most of the for
loop in your Python programming.
# Iterate over a range of numbers
for i in range(10):
print(i)
Output:-
1
2
3
4
5
6
7
8
9
This will output the numbers from 0 to 9. You can also use a for
loop to iterate over the elements of a list:
# Iterate over the elements of a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:-
apple
banana
cherry