How a for loop works
Python takes the first item from the sequence, stores it in the loop variable, runs the indented block, then moves to the next item. When there are no items left, the loop ends and Python continues with the code after it.
for i in range(3):
print("Hello", i)
print("Done")Output: Hello 0, Hello 1, Hello 2, then Done.
What range() gives you
range(5)→ 0, 1, 2, 3, 4 (stops before 5)range(2, 6)→ 2, 3, 4, 5range(0, 10, 2)→ 0, 2, 4, 6, 8
Looping over a list or string
fruits = ["apple", "mango"]
for fruit in fruits:
print(fruit)
for ch in "hi":
print(ch)Common beginner mistakes
- Forgetting the colon
:at the end of theforline. - Not indenting the loop body, so it runs only once (or causes an error).
- Expecting
range(5)to include 5 — it stops one before.
Practice exercises
Try each one yourself first, then open it in the Visualizer to watch every line run.
Exercise 1
Times table
Print the 7 times table from 7 x 1 to 7 x 10.
n = 7
for i in range(1, 11):
# print one line
passHint
range(1, 11) gives 1 to 10. Print n, "x", i, "=", n * i.
Show solution and explanation
n = 7
for i in range(1, 11):
print(n, "x", i, "=", n * i)The loop body runs 10 times. i takes each value from range in turn while n stays fixed.
Watch the solution step by stepExercise 2
Count the vowels
Count how many vowels are in a word.
word = "education"
count = 0
# loop over each letterHint
Use: if ch in "aeiou":
Show solution and explanation
word = "education"
count = 0
for ch in word:
if ch in "aeiou":
count = count + 1
print(count) # 5A for loop can walk through a string one letter at a time. count only grows when the condition is True.
Watch the solution step by stepExercise 3
Biggest number
Find the largest number in a list without using max().
nums = [12, 45, 7, 30]
biggest = nums[0]
# compare each numberHint
If x is greater than biggest, replace biggest.
Show solution and explanation
nums = [12, 45, 7, 30]
biggest = nums[0]
for x in nums:
if x > biggest:
biggest = x
print(biggest) # 45biggest starts as the first item and is only replaced when a larger one appears: 12 → 45, then 7 and 30 leave it unchanged.
Watch the solution step by step