Lesson 9 of 12
For Loops 🔄
What You'll Learn
- Use for loops to iterate over a range
- Loop through lists
- Use range() to control iterations
The For Loop
A for loop repeats code for each item in a sequence. It is perfect for going through lists or running code a specific number of times:
Python
# Loop through a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(f'I love {fruit}!')
# Loop 5 times using range()
for i in range(5):
print(f'Count: {i}')range() — Count with Control
Python
# range(stop)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# range(start, stop)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
# range(start, stop, step)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)Off by One
range(5) gives 0,1,2,3,4 (five numbers). range(1,6) gives 1,2,3,4,5. The stop value is never included!
Accumulating with Loops
Python
# Add up all numbers 1 to 100
total = 0
for num in range(1, 101):
total += num # same as total = total + num
print(total) # 5050Times Table
Ask the user for a number. Print its multiplication table from 1 to 10 using a for loop. Example: 3 x 4 = 12
Quick Check
What does range(3) produce?
What does += mean?
How do you loop through a list called 'items'?