Loops
Why loops exist and which kind to reach for
In this lesson
A loop runs a block of code repeatedly so you don’t have to copy and paste it — computers shine at doing the same thing many times without getting bored. This lesson is the map; the next two lessons dig into each loop type.
Explain it like I’m 5
A loop is ‘do this again’. Instead of writing the same instruction fifty times, you write it once and tell Python how many times — or how long — to keep doing it.
The two kinds of loop
Python has two loops. A for loop repeats once for each item in a collection — ‘for each name in this list, greet them’. A while loop repeats as long as a condition stays true — ‘keep asking until they type a valid answer’.
Rule of thumb: if you know what you’re looping over (a list, a range of numbers, the characters of a string), use for. If you’re looping until some condition changes and don’t know how many rounds that takes, use while.
for number in [1, 2, 3]:
print("Counting:", number)
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Go!")
Counting: 1 Counting: 2 Counting: 3 3 2 1 Go!
Iteration, one step at a time
Iteration means going through items one at a time. Each pass through the loop body is one iteration. A loop variable usually holds the current item, and it’s updated automatically on each pass. Understanding ‘what does the loop variable hold right now?’ is the key to reading any loop.
for letter in "cat":
print("this pass:", letter)
this pass: c this pass: a this pass: t
Steering a loop: break and continue
Two keywords change the flow inside any loop. break stops the loop immediately and moves on to the code after it — useful when you’ve found what you were looking for. continue skips the rest of the current iteration and jumps to the next one — useful for ‘ignore this item and carry on’.
for n in [1, 2, 3, 4, 5]:
if n == 3:
continue
print(n)
1 2 4 5
This loop prints the squares of 1–5. Add a break so it stops once the square passes 10.
for n in [1, 2, 3, 4, 5]:
square = n * n
print(n, "squared is", square)
Check if square > 10: before printing, and put break inside that if.
for n in [1, 2, 3, 4, 5]:
square = n * n
if square > 10:
break
print(n, "squared is", square)
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
The loop ‘else’ clause
A little-known feature: both for and while loops can have an else block. It runs only if the loop finished without hitting a break. That makes it a clean fit for search loops — break the moment you find what you want, and let the else handle the ‘never found it’ case.
It reads oddly at first (the else pairs with the loop, not an if), but it saves you from juggling a separate ‘found’ flag.
names = ["Ada", "Bo", "Cy"]
target = "Di"
for name in names:
if name == target:
print("Found", target)
break
else:
print(target, "is not in the list")
Di is not in the list
Common mistake: Reaching for while when for is simpler
Beginners often manually track a counter with while when they’re really just stepping through a known sequence.
If you’re counting through items or numbers, use a for loop with range() — it’s shorter and can’t accidentally loop forever.
You want to do something once for each item in a list. Which loop fits best?
for is built for stepping through the items of a collection.
What does break do inside a loop?
break exits the loop entirely; continue is the one that skips to the next iteration.
Mini exercise (easy)
Using a loop, print the numbers 1 through 5, but skip 3. Decide whether for or while is cleaner.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
kept = []
for n in range(1, 6):
# TODO: use continue to skip 3, otherwise keep n
kept.append(n)
print(kept)
A for loop over range(1, 6) with if n == 3: continue is the tidy version.
kept = []
for n in range(1, 6):
if n == 3:
continue
kept.append(n)
print(kept)
[1, 2, 4, 5]
__no_output_bypass__ = True
import ast as _ast
assert any(isinstance(n, _ast.Continue) for n in _ast.walk(_ast.parse(__user_code__))), "use a continue statement inside the loop to skip 3"
__no_output_bypass__ = False
assert kept == [1, 2, 4, 5], "keep 1, 2, 4, 5 and skip 3"
print("✓ Skipped 3!")