Loops: Repeating Work with for & while
Make the computer do the repetitive work: for loops over lists, strings and range, counting and adding up with loops, while loops that repeat until something happens, break and continue, loops inside loops, and how to avoid endless loops.
Why loops?
Computers are brilliant at doing the same thing many times without getting bored. A loop repeats a block of code. Without loops, printing 1,000 lines would need 1,000 print statements; with a loop it needs two lines.
Python has two kinds: a for loop repeats once for each item in a collection (each name in a list, each letter in a word, each number in a range), and a while loop repeats as long as a condition is True.
for loops: once for each item
Read for name in names: as "for each name in the list of names, do the indented block". On each pass (called an iteration), the loop variable name refers to the next item.
names = ["Sita", "Leo", "Mia"]
for name in names:
print("Hello,", name)
print("Done") # not indented: runs once, after the loop
for letter in "data": # a string is a sequence of characters
print(letter.upper())range: loops that count
range produces a sequence of whole numbers. Like slicing, it stops before the stop number:
range(5)→ 0, 1, 2, 3, 4 (five numbers, starting at 0)range(1, 6)→ 1, 2, 3, 4, 5range(0, 20, 5)→ 0, 5, 10, 15 (a step of 5)range(10, 0, -1)→ 10 down to 1
for i in range(5):
print("Lap", i)
for n in range(1, 11):
print(f"7 x {n} = {7 * n}")
for t in range(10, 0, -3):
print(t, end=" ")
print("lift off!")Adding up and counting with a loop
The most common loop pattern: start a variable before the loop (an accumulator), and update it on every pass. This is how you add up, count, or find the largest value.
prices = [4.5, 12.0, 3.25, 8.0, 15.5]
total = 0 # 1. start before the loop
for p in prices:
total += p # 2. update inside the loop
print("total:", total) # 3. use it after the loop
count_expensive = 0
for p in prices:
if p > 10:
count_expensive += 1
print("items over $10:", count_expensive)
biggest = prices[0]
for p in prices:
if p > biggest:
biggest = p
print("most expensive:", biggest)
# Python has built-ins for the simple cases:
print(sum(prices), max(prices), min(prices), len(prices))Watch a loop run
Step through the loop one line at a time. Watch n change on each pass and total grow only when the condition is True.
Interactive: this part runs in your browser.
enumerate and zip
Two helpers make loops shorter and clearer:
enumerate(items)gives each item with its position: no need for a separate counter.zip(a, b)walks two lists side by side, stopping at the shorter one.
names = ["Sita", "Leo", "Mia"]
scores = [82, 91, 77]
for position, name in enumerate(names, start=1):
print(position, name)
for name, score in zip(names, scores):
print(f"{name} scored {score}")while loops: repeat until something changes
A while loop checks its condition, runs the block if it is True, then checks again, and so on. Use it when you do not know in advance how many times to repeat: until a target is reached, until the user types "quit", until the model stops improving.
savings = 1000.0
years = 0
while savings < 2000: # keep going while this is True
savings = savings * 1.05 # 5% interest a year
years += 1
print(f"Doubled after {years} years: ${savings:,.2f}")
# count down
n = 3
while n > 0:
print(n)
n -= 1 # without this line the loop would never end
print("Go!")Endless loops
If nothing inside a while loop ever makes the condition False, it runs forever. The page or program freezes. On your computer, press Ctrl + C in the terminal to stop it; in the playground press Stop. Before running a while loop, ask: "what line makes the condition eventually False?"
break and continue
breakleaves the loop immediately.continueskips the rest of this pass and goes on to the next item.
A common pattern is while True: with a break inside: "keep asking until the answer is valid".
readings = [12, 15, -1, 14, 999, 13]
for r in readings:
if r < 0:
continue # skip bad values
if r == 999:
print("end marker found")
break # stop completely
print("reading:", r)
# find the first number divisible by 7 above 50
n = 50
while True:
n += 1
if n % 7 == 0:
break
print("first multiple of 7 after 50:", n)Loops inside loops
A loop can contain another loop. The inner loop runs completely for every single pass of the outer loop, so 3 outer passes × 4 inner passes = 12 runs of the inner block. Nested loops are how you work through grids, tables and every pair of items.
for row in range(1, 4):
line = ""
for col in range(1, 5):
line += f"{row * col:4}"
print(line)
sizes = ["S", "M"]
colours = ["red", "blue", "black"]
for s in sizes:
for c in colours:
print(s, c)Code example: variables, lists and loops
A worked example: read it step by step (every part is explained), then run it and experiment.
Interactive: this part runs in your browser.
Practice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Use a for loop with range to set total to the sum of the even numbers from 2 to 100 (inclusive). The answer is 2550.
Print the 7 times table from 1 to 10, one line each, in exactly this form:
7 x 1 = 7 7 x 2 = 14 … 7 x 10 = 70
Start with value = 3 and steps = 0. Use a while loop to double value until it is greater than 1000, counting the doublings in steps. At the end value is 1536 and steps is 9.
Summary
for loops repeat once per item (use range to count); while loops repeat while a condition is True. Accumulators add up and count; enumerate and zip keep loops tidy; break stops a loop and continue skips one pass.
Key words
- loop
- code that repeats
- iteration
- one pass through a loop
- loop variable
- the name that takes each item in turn (
for item in …) - range
- a sequence of whole numbers:
range(start, stop, step) - accumulator
- a variable that builds up a result over the loop (a total, a count)
- infinite loop
- a loop that never stops because its condition never becomes False
- break / continue
- leave the loop / skip to the next pass
- nested loop
- a loop inside another loop
Common mistakes
- Forgetting that
range(1, 10)stops at 9. - Setting the accumulator inside the loop (
total = 0on every pass), so it resets each time. - Indenting the final print inside the loop, so it prints on every pass instead of once at the end.
- A while loop whose condition never becomes False: make sure something in the loop changes it.
- Changing a list (adding or removing items) while looping over it. Loop over a copy,
for x in items[:]:, or build a new list. - Using
range(len(names))andnames[i]whenfor name in names(or enumerate) is simpler.
Quiz
1. What does list(range(3)) give?
2. How many times does "hi" print?for i in range(2, 10, 2): print("hi")
3. What does continue do?
4. Which situation suits a while loop better than a for loop?
5. With two nested loops of 3 and 5 passes, how many times does the inner block run?
6. Which is the clearest way to loop over items and their positions?