Loops: for & while
Lesson 6 of 7 · View course roadmap
Learn the idea
Loops let you repeat work without repeating code — the superpower that makes computers useful.
for loops walk through a sequence. range(5) produces 0,1,2,3,4 (start at 0, stop before 5). range(1, 6) gives 1–5.
while loops repeat as long as a condition stays True — perfect when you don't know how many repetitions you need.
break— exit the loop immediatelycontinue— skip to the next iteration- Beware infinite while loops — make sure something changes the condition!
Where you'll use this
Loops process every row of a spreadsheet, every user in a database, every line of a log file. 'For each order, send an email' — that sentence is a for loop, and automation careers are built on it.
Common mistakes
- Off-by-one with range:
range(5)is 0–4. Want 1–5?range(1, 6). - Infinite while loops — forgetting to change the loop variable inside the body.
- Modifying a list while looping over it — skips elements unpredictably. Loop over a copy:
for x in items[:].
Pro tip
Need the index AND the value? Never do range(len(items)) — use enumerate: for i, item in enumerate(items). Looping two lists together? zip(names, scores).
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +30 XP
Use a for loop with range to print the squares of the numbers 1 through 5, one per line (1, 4, 9, 16, 25).
1 4 9 16 25
range(1, 6) gives 1..5; square with i ** 2.
for i in range(1, 6):
print(i ** 2)
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.