Doing the same job a hundred times
A loop repeats a block of code, so a Python program can do one job many times without you writing it out again. It is how a program adds up a column of prices, checks every line of a log or counts the days to a deadline.
Typing print a hundred times would be silly. A loop does it in two lines.
By the end of this lesson
Note
I can repeat work with for and while loops.
Key words
| Word | What it means | Example |
|---|---|---|
| Loop | code that repeats | |
| Iteration | one pass through a loop | |
| Range | a run of whole numbers made by range() | range(1, 6) |
| Accumulator | a variable that builds up a total as a loop runs | total |
| Infinite loop | a loop that never ends | |
| Break | a command that leaves a loop early |
The cells students fill in are left blank in this preview.
A for loop repeats once for each value
A for loop takes a run of values and repeats its indented lines once for each. The name after for holds the current value.
range makes the run of whole numbers. range(5) gives 0 to 4. range(1, 6) gives 1 to 5, because it stops before the second number.
Worked example: what range gives
| You write | You get | Number of passes |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | 5 |
| range(2, 10, 2) | 2, 4, 6, 8 | 4 |
| range(10, 0, -3) | 10, 7, 4, 1 | 4 |
The cells students fill in are left blank in this preview.
Print three numbers
python3 -c "for n in range(3): print(n)"Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.
Five rounds
for n in range(1, 6):
print("Round", n)
# Change 6 to 9 and run again.
A common mistake
Warning
Many people think range(1, 5) includes 5. It stops before 5, so it gives 1, 2, 3 and 4. To count up to 5, write range(1, 6). The end number is never part of the run.
An accumulator builds up a total
To add up many values, make a variable before the loop and start it at 0. Inside the loop, add each value to it. This variable is an accumulator.
After the loop it holds the whole total. The trace table shows each pass.
Worked example: adding 1 to 4
| Pass | n | total after the pass |
|---|---|---|
| Before the loop | none | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
The cells students fill in are left blank in this preview.
Watch the total grow
total = 0
for n in range(1, 5):
total = total + n
print("n is", n, "and total is", total)
print("Final total:", total)
Save a loop program as a file
printf 'total = 0\nfor n in range(1, 5):\n total = total + n\nprint(total)\n' > total.pyShown here, not run. Create a free account to press Run and type it into your own lab’s terminal.
Run the file
python3 total.pyShown here, not run. Create a free account to press Run and type it into your own lab’s terminal.
A while loop repeats on a condition
A while loop does not need a run of values. It tests a condition before every pass, and it repeats while the condition is True.
Something inside the loop must change the answer, or it never stops. A loop that never ends is an infinite loop. In a terminal, press Ctrl and C together to stop one.
Saving until the balance is enough
balance = 100
months = 0
while balance < 150:
balance = balance + 20
months = months + 1
print(months, "months to reach", balance)
# Change 150 to 200 and run again.
break leaves a loop early
Sometimes you can stop as soon as you find what you want. The command break leaves the loop at once, and the program carries on after it.
The next program searches for the first number whose square is over 50.
Stop at the first square over 50
for n in range(1, 100):
if n * n > 50:
print("First square over 50 is", n * n)
break
A nested loop runs inside another loop
A loop can sit inside another loop. The inner loop runs all its passes for each pass of the outer one.
With 2 passes outside and 3 inside, the inner lines run 2 times 3, which is 6 times.
Six lines from two loops
for row in range(1, 3):
for col in range(1, 4):
print(row, "x", col, "=", row * col)
# The inner loop runs fully for each pass of the outer one.
A small table from one line
python3 -c "for a in range(1, 4): print(a, a * 2, a * 3)"Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.
Going further
Change total.py so that it adds the even numbers from 2 to 20. You can do it with a third number in range, or with an if inside the loop.
Write down the answer you expect first. A trace table for the first three passes is enough to check it.