Introduction
A for loop helps you repeat actions easily. It goes through items one by one and does something with each.
Jump into concepts and practice - no test required
A for loop helps you repeat actions easily. It goes through items one by one and does something with each.
for item in collection: # do something with item
item is a temporary name for each element as the loop runs.
collection can be a list, string, or any group of items.
for number in [1, 2, 3]: print(number)
for letter in 'cat': print(letter)
for i in range(3): print('Hello')
This program goes through each fruit in the list and prints a sentence saying you like it.
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(f'I like {fruit}')
The loop runs once for each item in the collection.
Indentation (spaces before the code inside the loop) is very important in Python.
If the collection is empty, the loop does not run at all.
A for loop repeats actions for each item in a group.
It helps avoid writing the same code many times.
Use it when you want to work with every item in a list, string, or range.
for loop do in Python?for i in range(3):
print(i * 2)for i in range(5)
print(i)