Programming in Python / Repeated work
Repeated work
All 5 lessons, in order.
The unit at a glance
- Read a for loop
A ticket checker at a gate takes the tickets of the people in line one at a time, from the front, and does the same check on each.
- Choose the bounds of range
A row of seats is numbered from a first seat up to a sign that says where the row ends.
- Trace a while loop
Someone filling a bucket from a tap looks at it before each scoop: if it is not full yet, one more scoop goes in, and then they look again.
- Keep a running total
Picture a cashier starting a sale at 0.
- Stop a search at a match
Someone looking for keys opens one drawer after another.
Rules (5)
- Read a for loop
A for loop over a sequence runs its indented body once for each item, in order, unless a
breakends it sooner. Before each pass, the name afterforis given the next item. When the items run out, the program carries on with the first line after the body. An empty sequence gives no passes. - Choose the bounds of range
range(stop)gives the whole numbers from 0 up to but not includingstop.range(start, stop)starts atstartwhenstartis belowstop, and is empty otherwise.range(start, stop, step)moves bystepeach time and holds the numbers belowstopfor a positive step, or abovestopfor a negative one.stopis never included, and a step of 0 raises a ValueError. - Trace a while loop
A while loop tests its condition before every pass. While the condition is true, it runs the indented body and, when the body reaches its end, goes back to the test; a
breakends it sooner. When the condition is false, the program carries on with the first line after the body, and a condition that is false at the first test gives no passes. - Keep a running total
A running total or a count is set to its starting value before the loop and changed inside the body, so each pass builds on the last. The biggest value so far starts with the first value and is replaced inside the loop when an
iffinds a bigger one.x += 1adds 1 tox. - Stop a search at a match
A
breakline ends the nearest loop around it at once, skips the rest of that pass and every later pass, and the program carries on with the first line after the loop. After abreak, a for loop's name keeps its current item.
Recipes (5)
- Read a for loop
- Find the sequence after
inand write its items in order. A string gives one item for each character. - Find the body: the lines indented under the
forline. - For each item, write the loop name's value, then run the body's lines in order with that value.
- After the last pass, move to the first line after the body. In this unit's programs that is the next line indented no further than the
forline. - Count the passes: one for each item, unless a
breakends the loop sooner. Check that the output holds what the body displays once for each pass.
- Find the sequence after
- Choose the bounds of range
- Write the first number you want. That is
start. It can be left out when it is 0 and no step is given, because a step needs a start before it. - Choose the step. Leave it out to count up by 1, write a bigger number as the third number to skip, or a negative one to count down.
- Write the last number you want, and check that counting from
startby the step lands on it; if it does not, change the start or the step. Then setstoppast it, no more than one step beyond it: above it when counting up, below it when counting down. For a count up by 1,stopis the last number plus 1. Inrange(10, 0, -3)the last number is 1, and the stop 0 lies below it, within one step of 3. - Check the count: for a step of 1 and a
stopabovestart,range(start, stop)givesstopminusstartnumbers. - Write out the numbers the range gives, or note that it gives none, and compare them with what you wanted.
- Write the first number you want. That is
- Trace a while loop
- Write each name the condition uses, with its value before the loop.
- Test the condition with those values. If it is false, skip to the first line after the body.
- If it is true, run the body's lines in order and write each name's new value.
- Find what can make the condition false at a later test: a line in the body that changes a name it reads, or a new value it reads each time, such as a reply from
input(). If nothing can, and nothing else ends the loop, such as thebreakof this unit's last lesson, the loop will not end on its own. - Go back to the test with the new values, and repeat until a test is false or something ends the loop sooner.
- Keep a running total
- Decide what to keep: a total, a count or the biggest value.
- Before the loop, give it a starting value: 0 for a total or a count, the first value for the biggest. A line such as
total = total + stepsreads the name before it changes it, so the name needs a value first. - Inside the body, change it on the passes that need it: add each value to a total, add 1 when a pass matches, or replace the biggest when an
iffinds a bigger value. - After the loop, use the result: display it, or, when the count is above 0, divide the total by the count for an average.
- Trace two passes by hand and check that the value after each pass builds on the one before.
- Stop a search at a match
- Above the loop, set any name that the program reads after the loop and that only a match changes, such as
found = False. - Write the test that marks a match, and put it in an
ifinside the body. - Inside that
if, do what the match needs, such as settingfound = True, and then writebreak. - Trace the passes until the test is true. At the
break, jump to the first line after the loop. - Check the case with no match. A for loop runs to its end, and a name that only a match changes, such as
found, still holds the value it was given above the loop. Awhile True:loop that reads input and meets no match keeps reading; when the input runs out,input()stops the program with an EOFError.
- Above the loop, set any name that the program reads after the loop and that only a match changes, such as
Traps (5)
- Read a for loop
A line meant to run once can slip into the body. If
print("done")were indented under theforline, it would run on every pass and the output would hold done three times. Check the indentation of each line below aforline.The loop name keeps its last value after the loop ends. After the loop over
"MAP",letterstill holdsP. Use the loop name inside the body, where it holds the current item. - Choose the bounds of range
The usual slip is a stop one short.
range(1, 5)ends at 4, so a loop meant to count to 5 needsrange(1, 6). Write out the last number of the range before you run the program.Counting down needs a negative step.
range(5, 1)holds no numbers, because its step is 1 and 5 is not below 1. The loop makes no passes and nothing is displayed. Writerange(5, 1, -1)for 5, 4, 3 and 2. - Trace a while loop
Leave out the line that changes the name, and the condition never becomes false. A countdown without
seconds = seconds - 1displays 3 again and again and never ends. Press Control-C, the interrupt key, to stop it; Python stops the program with a KeyboardInterrupt.The other slip is the edge of the condition.
seconds > 0stops before 0 is displayed, andseconds >= 0displays 0 as well. Trace the last two tests to see which values get a pass. - Keep a running total
A total set to 0 at the top of the body starts again on every pass. With
total = 0as the body's first line, the step program would displayTotal: 4000, the last day's steps alone, andAverage: 1000.0, that one day divided by 4. Put the starting value above theforline.Starting the biggest value at 0 goes wrong when every value is below 0: no value is bigger than 0, so the program would display 0, a number that was never read. Start with the first value instead, as the worked example does.
- Stop a search at a match
A message about a miss written in the body after the match test runs on every pass that misses: in a search for a space, once for each character before the space, or once for every character of a string with no space. Decide after the loop, with a name such as
found, whether the search found nothing.In a
while True:loop, the test never ends the loop. If the test before thebreakis never true for the replies typed, as when each reply is compared with"Done"and the person types done each time, the loop keeps asking. It stops only with an error: an EOFError when the input runs out, or a KeyboardInterrupt when you press Control-C, the interrupt key.
Lesson 1 of 5
Read a for loop
Open this lessonLeans on 1Comes back in 0
Leans on
Comes back in
No lesson links recorded.
1 In plain words
A ticket checker at a gate takes the tickets of the people in line one at a time, from the front, and does the same check on each. When the line is empty, the checker stops.
A for loop works through the items of a sequence in the same way. It runs its indented body once for each item, in the order the items appear. A string is a sequence of characters, so a for loop over a string runs its body once for each character.
Before each pass, the name after for, the loop name, is given the next item. The body can use that name to work with the current item.
A break, taught in the last lesson of this unit, can end a loop sooner.
Remember one sentence: a for loop gives its name each item in turn and runs the body once for each, unless a break ends it sooner. To look it up, see section 4.2 of the Python 3.13 tutorial, on for statements.
2 Picture it
A table of the three passes of a for loop over the string MAP. On pass 1 the name letter holds M and the body displays M. On pass 2 it holds A and the body displays A. On pass 3 it holds P and the body displays P. These are the passes of the first worked example. The first row is marked.
3 Why
Python works out the sequence once, at the for line. It then gives the loop name the first item and runs the body. When the body reaches its end, the loop name gets the next item and the body runs again. When there is no next item, the loop ends and Python carries on with the first line after the body.
The body is the block of lines indented under the for line. The lines directly in it share one indentation; a block inside it, such as an if block, is indented further. The first line after the body, indented no further than the for line, is not part of the loop. In the programs of this unit it runs once, when the loop has ended.
A sequence with no items gives no passes. A for loop over the empty string "" never runs its body, and the loop name is not given a value by the loop.
4 The rule
A for loop over a sequence runs its indented body once for each item, in order, unless a break ends it sooner.
Before each pass, the name after for is given the next item. When the items run out, the program carries on with the first line after the body. An empty sequence gives no passes.
5 How
- Find the sequence after
inand write its items in order. A string gives one item for each character. - Find the body: the lines indented under the
forline. - For each item, write the loop name's value, then run the body's lines in order with that value.
- After the last pass, move to the first line after the body. In this unit's programs that is the next line indented no further than the
forline. - Count the passes: one for each item, unless a
breakends the loop sooner. Check that the output holds what the body displays once for each pass.
6 Worked example
Display each character of a string
for letter in "MAP":
print(letter)
print("done")
Standard input
Empty
Standard output
M
A
P
done
Predict the four output lines first. Then save the code as letters.py and run the file, or follow the trace below. The body runs once for each of the three characters, and done is displayed once, after the loop.
A body of two lines
for letter in "ab":
print(letter)
print("-")
print("end")
Standard input
Empty
Standard output
a
-
b
-
end
Both print lines are indented, so both belong to the body and both run on each pass. The last line is at the margin, so it runs once.
Trace
| Step | letter | Output | Explanation |
|---|---|---|---|
| Pass 1 | M | M | The loop name gets the first character, and the body displays it. |
| Pass 2 | A | A | The loop name gets the next character, and the body runs again. |
| Pass 3 | P | P | The last character. After this pass there is no next item. |
print("done") | P | done | The loop has ended. The line at the margin runs once. |
7 The trap
A line meant to run once can slip into the body. If print("done") were indented under the for line, it would run on every pass and the output would hold done three times. Check the indentation of each line below a for line.
The loop name keeps its last value after the loop ends. After the loop over "MAP", letter still holds P. Use the loop name inside the body, where it holds the current item.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
for c in "hi":
print(c)
print(c)Show the steps and the answer
It displays h, h, i and i, each on its own line.
Why: The string has two characters, so the body runs twice. Both print lines are in the body, so each pass displays its character twice.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
Quick check 2 of 2
Predict what this program displays. The program reads no input.
word = ""
for ch in word:
print("x")
print("after")Show the steps and the answer
It displays only after.
Why: The empty string has no characters, so the loop makes no passes and its body never runs. The last line is at the margin and runs once.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
Sources
- Python 3.13 Tutorial, 4.2 for Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.3 The for statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 3.2 First Steps Towards Programming. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 2 of 5
Choose the bounds of range
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A row of seats is numbered from a first seat up to a sign that says where the row ends. The sign itself is not a seat.
range makes a sequence of whole numbers for a for loop. range(stop) counts 0, 1, 2 and so on, and ends before stop. range(start, stop) counts up from start instead, when start is below stop. A third number, the step, sets how far each number is from the one before, and a negative step counts down.
The number given as stop is never in the sequence. range(5) gives 0, 1, 2, 3 and 4: five numbers, and 5 is not one of them.
Remember one sentence: range counts from its start and stops before its stop. To look it up, see section 4.3 of the Python 3.13 tutorial, on the range() function.
2 Picture it
A table of three calls of range. range(5) gives 0 1 2 3 4. range(1, 6) gives 1 2 3 4 5. range(5, 0, -1) gives 5 4 3 2 1. Each list starts at the start and moves by the step up to, but not including, the stop, as the rule of this lesson says. The row for range(1, 6) is marked.
3 Why
A range's first number is start, which is 0 when only one number is given, as long as it meets the bound below. Each next number is the one before plus the step, which is 1 when no step is given.
With a positive step, the sequence holds the numbers below stop. With a negative step, it holds the numbers above stop. So range(1, 6) ends at 5, and range(10, 0, -3) gives 10, 7, 4 and 1: the next number, -2, is not above 0. When the first number already fails that test, as in range(5, 1), the range is empty and the loop makes no passes.
A step of zero would never move. range refuses it: a step of 0 stops the program with a ValueError.
4 The rule
range(stop) gives the whole numbers from 0 up to but not including stop.
range(start, stop) starts at start when start is below stop, and is empty otherwise. range(start, stop, step) moves by step each time and holds the numbers below stop for a positive step, or above stop for a negative one. stop is never included, and a step of 0 raises a ValueError.
5 How
- Write the first number you want. That is
start. It can be left out when it is 0 and no step is given, because a step needs a start before it. - Choose the step. Leave it out to count up by 1, write a bigger number as the third number to skip, or a negative one to count down.
- Write the last number you want, and check that counting from
startby the step lands on it; if it does not, change the start or the step. Then setstoppast it, no more than one step beyond it: above it when counting up, below it when counting down. For a count up by 1,stopis the last number plus 1. Inrange(10, 0, -3)the last number is 1, and the stop 0 lies below it, within one step of 3. - Check the count: for a step of 1 and a
stopabovestart,range(start, stop)givesstopminusstartnumbers. - Write out the numbers the range gives, or note that it gives none, and compare them with what you wanted.
6 Worked example
Count from 1 to 5
for n in range(1, 6):
print(n)
Standard input
Empty
Standard output
1
2
3
4
5
The last number wanted is 5, so stop is 6. Save the code as count.py and run the file.
Count down by 3
for n in range(10, 0, -3):
print(n)
Standard input
Empty
Standard output
10
7
4
1
The step is -3, so each number is 3 less than the one before. The trace below shows why the loop ends after 1.
Number three laps from 1
for lap in range(1, 4):
print(f"Lap {lap}")
Standard input
Empty
Standard output
Lap 1
Lap 2
Lap 3
range(1, 4) gives 1, 2 and 3: three numbers, starting at 1 and stopping before 4.
Give range a step of zero
for n in range(0, 10, 0):
print(n)
Standard input
Empty
Standard output
Empty
Exception ValueError
Save the two lines as zero.py and run the file. The program stops with a ValueError at the for line, before the body runs once.
Trace
| Step | n | Above 0? | Explanation |
|---|---|---|---|
| Pass 1 | 10 | yes | The start is 10, and the body displays 10. |
| Pass 2 | 7 | yes | 10 plus the step of -3 is 7. |
| Pass 3 | 4 | yes | 7 minus 3 is 4. |
| Pass 4 | 1 | yes | 4 minus 3 is 1, which is still above the stop of 0. |
| Next: -2 | 1 | no | The next number would be -2, which is not above 0. It is not in the range, so the loop ends and n still holds 1. |
7 The trap
The usual slip is a stop one short. range(1, 5) ends at 4, so a loop meant to count to 5 needs range(1, 6). Write out the last number of the range before you run the program.
Counting down needs a negative step. range(5, 1) holds no numbers, because its step is 1 and 5 is not below 1. The loop makes no passes and nothing is displayed. Write range(5, 1, -1) for 5, 4, 3 and 2.
Quick checks
Quick check 1 of 2
Which numbers does range(2, 9, 3) give?
Show the steps and the answer
It gives 2, 5 and 8.
Why: It starts at 2 and adds 3 each time. The next number, 11, is not below 9, so the range ends at 8.
Source: Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Ranges
Quick check 2 of 2
Write a call of range that gives the whole numbers from 1 to 10, with both 1 and 10 included.
Show the steps and the answer
range(1, 11)
Why: The start is 1. The stop is never included, so it is one more than the last number wanted, 10.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.3 The range() Function
Sources
- Python 3.13 Tutorial, 4.3 The range() Function. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Ranges. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.3 The for statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 4.2 for Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 3 of 5
Trace a while loop
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Someone filling a bucket from a tap looks at it before each scoop: if it is not full yet, one more scoop goes in, and then they look again. Once it is full, they stop.
A while loop repeats in the same way. It tests its condition, and when the condition is true it runs the indented body. Then it goes back and tests the condition again.
When the test gives false, the loop ends and Python carries on with the first line after the body. That can happen at the first test, and then the body never runs.
Remember one sentence: a while loop tests before every pass. To look it up, see section 3.2 of the Python 3.13 tutorial, First Steps Towards Programming.
2 Picture it
A table of the four tests of a countdown loop. When seconds is 3, 2 and 1 the condition seconds > 0 is True, and the body runs. When seconds is 0 the condition is False, and the loop ends. These are the tests of the countdown worked example. The last row is marked.
3 Why
Each pass has two parts: the test, then the body. Python tests the condition first. If it is true, Python runs the body, and when the body reaches its end it goes back to the test.
For the test to end the loop, the condition has to become false at some test; otherwise the loop goes on until something else ends it, such as the break of this unit's last lesson. A line in the body can change a name the condition reads: in the guessing example, guess = input() gives guess a new reply on each pass. In the countdown program the line seconds = seconds - 1 makes the number smaller on each pass. When it reaches 0, the test seconds > 0 gives False and the loop ends.
A while loop fits when the number of passes is not known in advance: keep asking until a reply is right, or keep adding until a total reaches a goal. A for loop fits when there is a known sequence to work through.
4 The rule
A while loop tests its condition before every pass.
While the condition is true, it runs the indented body and, when the body reaches its end, goes back to the test; a break ends it sooner. When the condition is false, the program carries on with the first line after the body, and a condition that is false at the first test gives no passes.
5 How
- Write each name the condition uses, with its value before the loop.
- Test the condition with those values. If it is false, skip to the first line after the body.
- If it is true, run the body's lines in order and write each name's new value.
- Find what can make the condition false at a later test: a line in the body that changes a name it reads, or a new value it reads each time, such as a reply from
input(). If nothing can, and nothing else ends the loop, such as thebreakof this unit's last lesson, the loop will not end on its own. - Go back to the test with the new values, and repeat until a test is false or something ends the loop sooner.
6 Worked example
Count down to Go
seconds = 3
while seconds > 0:
print(seconds)
seconds = seconds - 1
print("Go")
Standard input
Empty
Standard output
3
2
1
Go
Predict the four lines first. Then save the code as countdown.py and run the file, or follow the trace below.
Save until the goal is reached
balance = 50
weeks = 0
while balance < 100:
balance = balance + 20
weeks = weeks + 1
print(weeks)
print(balance)
Standard input
Empty
Standard output
3
110
The program does not know in advance how many weeks it takes. After 3 weeks the balance is 110. That is not below 100, so the loop ends, one week past 90.
Ask again until the reply is right
guess = input()
while guess != "blue":
print("Try again")
guess = input()
print("Yes")
Standard input
red
green
blue
Standard output
Try again
Try again
Yes
Type red, green and blue, one a line. The first two replies keep the condition true. blue makes it false, so the loop ends and Yes is displayed.
Trace
| Line | seconds | Output | Explanation |
|---|---|---|---|
seconds = 3 | 3 | — | The name the condition uses gets its first value. |
| Test, then pass 1 | 3 then 2 | 3 | 3 > 0 is True. The body displays 3, then makes seconds 2. |
| Test, then pass 2 | 2 then 1 | 2 | 2 > 0 is True. The body displays 2, then makes seconds 1. |
| Test, then pass 3 | 1 then 0 | 1 | 1 > 0 is True. The body displays 1, then makes seconds 0. |
| Test | 0 | — | 0 > 0 is False, so the loop ends. |
print("Go") | 0 | Go | The first line after the body runs once. |
7 The trap
Leave out the line that changes the name, and the condition never becomes false. A countdown without seconds = seconds - 1 displays 3 again and again and never ends. Press Control-C, the interrupt key, to stop it; Python stops the program with a KeyboardInterrupt.
The other slip is the edge of the condition. seconds > 0 stops before 0 is displayed, and seconds >= 0 displays 0 as well. Trace the last two tests to see which values get a pass.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
count = 10
while count > 4:
count = count - 3
print(count)Show the steps and the answer
It displays 4.
Why: 10 > 4 is true, so count becomes 7. 7 > 4 is true, so count becomes 4. 4 > 4 is false, so the loop ends and 4 is displayed.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.2 The while statement
Quick check 2 of 2
Predict what this program displays. The program reads no input.
x = 5
while x < 3:
print("x")
x = x + 1
print("done")Show the steps and the answer
It displays only done.
Why: 5 < 3 is false at the first test, so the body never runs. The line after the body runs once.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.2 The while statement
Sources
- Python 3.13 Language Reference, 8.2 The while statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 3.2 First Steps Towards Programming. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 4.2 for Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: input. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: KeyboardInterrupt. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 4 of 5
Keep a running total
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Picture a cashier starting a sale at 0. Each item adds its price, and the screen shows the total so far.
A loop can keep a running total in the same way. A name is set to 0 before the loop, and each pass adds one value to it. After the loop, the name holds the sum of every value.
The same plan keeps a count: start at 0 and add 1 on each pass that matches. It also keeps the biggest value so far: start with the first value, and replace it on any pass that finds a bigger one.
Remember one sentence: set the total before the loop and add to it inside. To look up the short form count += 1, see section 7.2.1 of the Python 3.13 language reference, on augmented assignment.
2 Picture it
A table of the four passes of the step-count program. The total starts at 0. After the first pass it is 4000, after the second 10500, after the third 16000 and after the fourth 20000. The values are the input of the first worked example. The last row is marked.
3 Why
The line total = total + steps works out the right side first, with the total so far, and then gives the name total the new value. Each pass builds on the value the last pass left.
The total needs a value before the first line that reads it, so the programs here set it above the loop. A line total = 0 at the top of the body would wipe out the total at the start of each pass, and only the last value would be left at the end.
An average is the total divided by the number of values. Dividing with / gives a float, so 20000 / 4 displays as 5000.0, with a decimal point. The short form count += 1 adds 1 to count and gives it the new value, much like count = count + 1.
- Python Software Foundation, Python 3.13 Tutorial, 3.2 First Steps Towards Programming
- Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
4 The rule
A running total or a count is set to its starting value before the loop and changed inside the body, so each pass builds on the last.
The biggest value so far starts with the first value and is replaced inside the loop when an if finds a bigger one. x += 1 adds 1 to x.
5 How
- Decide what to keep: a total, a count or the biggest value.
- Before the loop, give it a starting value: 0 for a total or a count, the first value for the biggest. A line such as
total = total + stepsreads the name before it changes it, so the name needs a value first. - Inside the body, change it on the passes that need it: add each value to a total, add 1 when a pass matches, or replace the biggest when an
iffinds a bigger value. - After the loop, use the result: display it, or, when the count is above 0, divide the total by the count for an average.
- Trace two passes by hand and check that the value after each pass builds on the one before.
6 Worked example
Add up four days of steps
total = 0
for day in range(4):
steps = int(input())
total = total + steps
average = total / 4
print(f"Total: {total}")
print(f"Average: {average}")
Standard input
4000
6500
5500
4000
Standard output
Total: 20000
Average: 5000.0
Type the four numbers one a line, or follow the table above. Each pass reads one number and adds it to the total. The average is worked out in a name of its own before it is displayed.
Keep the biggest score so far
biggest = int(input())
for turn in range(3):
score = int(input())
if score > biggest:
biggest = score
print(biggest)
Standard input
12
40
33
40
Standard output
40
The first score, 12, is the biggest so far. 40 replaces it. 33 and the second 40 are not bigger than 40, so biggest does not change, though score does.
Count the letter a
count = 0
for ch in "banana":
if ch == "a":
count += 1
print(count)
Standard input
Empty
Standard output
3
The count goes up by 1 only on the passes where the character is a, because the if runs its block only then. banana has three of them.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Tutorial, 3.2 First Steps Towards Programming
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
Trace
| Step | score | biggest | Explanation |
|---|---|---|---|
| Before the loop | — | 12 | The first number read is the biggest so far. |
| Pass 1 | 40 | 40 | 40 > 12 is True, so biggest becomes 40. |
| Pass 2 | 33 | 40 | 33 > 40 is False, so biggest stays 40. |
| Pass 3 | 40 | 40 | 40 > 40 is False, so biggest stays 40. |
print(biggest) | 40 | 40 | After the loop, the line at the margin displays 40. |
7 The trap
A total set to 0 at the top of the body starts again on every pass. With total = 0 as the body's first line, the step program would display Total: 4000, the last day's steps alone, and Average: 1000.0, that one day divided by 4. Put the starting value above the for line.
Starting the biggest value at 0 goes wrong when every value is below 0: no value is bigger than 0, so the program would display 0, a number that was never read. Start with the first value instead, as the worked example does.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
total = 0
for n in range(2, 11, 2):
total = total + n
print(total)Show the steps and the answer
It displays 30.
Why: The range gives 2, 4, 6, 8 and 10. Adding them one a pass gives 2, 6, 12, 20 and then 30.
Source: Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Ranges
Quick check 2 of 2
Predict what this program displays. The program reads no input.
for n in range(1, 5):
total = 0
total = total + n
print(total)Show the steps and the answer
It displays 4.
Why: Each pass sets total to 0 and then adds that pass's number. After the last pass, with n holding 4, total is 4.
Source: Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
Sources
- Python 3.13 Tutorial, 3.2 First Steps Towards Programming. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 7.2.1 Augmented assignment statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.3 The for statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 3.1.1 Numbers. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: int. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: input. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Ranges. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 5 of 5
Stop a search at a match
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Someone looking for keys opens one drawer after another. When the keys turn up, they stop: the drawers further along are not opened.
A loop stops early with break. When Python runs a break line, it ends the loop at once, and the program carries on with the first line after the loop.
In this lesson's searches the break sits inside an if in the body, so it runs only when the test finds a match. With no match, a for loop runs to the end of its sequence. while True: makes a loop whose test is always true, so the test never ends it. A break does, and so does an error that stops the program, such as the EOFError of input() when the input runs out.
Remember one sentence: break leaves the loop now. To look it up, see section 4.4 of the Python 3.13 tutorial, on break and continue.
- Python Software Foundation, Python 3.13 Tutorial, 4.4 break and continue Statements
- Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
- Python Software Foundation, Python 3.13 Language Reference, 8.2 The while statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
2 Picture it
A table of the passes of a loop that searches the string plan B for a space. On passes 1 to 4 the characters p, l, a and n do not match and are displayed. On pass 5 the space matches and break ends the loop. The character B is never reached. These are the passes of the first worked example. The row for the match is marked.
3 Why
break ends the loop that holds it, not only the if around it. Python skips the rest of the body and every pass that was still to come.
After a break in a for loop, the loop name keeps the value it held when the break ran: in this lesson's searches, the item that matched. A program can read it after the loop to see where the search stopped.
A loop that stops at a match can also end without one. Set a name such as found = False before the loop and make it True right before the break. After the loop, that name says which way the search ended.
4 The rule
A break line ends the nearest loop around it at once, skips the rest of that pass and every later pass, and the program carries on with the first line after the loop.
After a break, a for loop's name keeps its current item.
5 How
- Above the loop, set any name that the program reads after the loop and that only a match changes, such as
found = False. - Write the test that marks a match, and put it in an
ifinside the body. - Inside that
if, do what the match needs, such as settingfound = True, and then writebreak. - Trace the passes until the test is true. At the
break, jump to the first line after the loop. - Check the case with no match. A for loop runs to its end, and a name that only a match changes, such as
found, still holds the value it was given above the loop. Awhile True:loop that reads input and meets no match keeps reading; when the input runs out,input()stops the program with an EOFError.
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
- Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
6 Worked example
Stop at the first space
for ch in "plan B":
if ch == " ":
print("space found")
break
print(ch)
print("after")
Standard input
Empty
Standard output
p
l
a
n
space found
after
Predict the output first. Then save the code as space.py and run the file. The B after the space is never displayed, because the loop ends at the space.
Read words until done
count = 0
while True:
word = input()
if word == "done":
break
count = count + 1
print(count)
Standard input
fern
moss
done
ivy
Standard output
2
The input holds four lines: fern, moss, done and ivy. The loop counts two words and ends at done, so ivy is never read.
Find the first square over 200
found = False
for n in range(1, 50):
if n * n > 200:
found = True
break
print(found)
print(n)
Standard input
Empty
Standard output
True
15
14 times 14 is 196 and 15 times 15 is 225, so the search stops at 15. After the break, n still holds 15.
- Python Software Foundation, Python 3.13 Tutorial, 4.4 break and continue Statements
- Python Software Foundation, Python 3.13 Language Reference, 8.2 The while statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
Trace
| Pass | word | count after the pass | Explanation |
|---|---|---|---|
| 1 | fern | 1 | fern is not done, so the if block is skipped and the count goes up to 1. |
| 2 | moss | 2 | moss is not done, so the if block is skipped and the count goes up to 2. |
| 3 | done | 2 | The test matches and break ends the loop before the count line. |
print(count) | done | 2 | The line after the loop displays 2. The fourth line of input is never read. |
7 The trap
A message about a miss written in the body after the match test runs on every pass that misses: in a search for a space, once for each character before the space, or once for every character of a string with no space. Decide after the loop, with a name such as found, whether the search found nothing.
In a while True: loop, the test never ends the loop. If the test before the break is never true for the replies typed, as when each reply is compared with "Done" and the person types done each time, the loop keeps asking. It stops only with an error: an EOFError when the input runs out, or a KeyboardInterrupt when you press Control-C, the interrupt key.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
for ch in "cab":
if ch == "a":
break
print("no match")Show the steps and the answer
It displays no match once.
Why: On the first pass ch holds c, which is not a, so the line no match is displayed. On the second pass ch holds a and break ends the loop, so b is never reached.
Source: Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
Quick check 2 of 2
Predict what this program displays when the input lines are 3, 8, 0 and 5.
total = 0
while True:
n = int(input())
if n == 0:
break
total = total + n
print(total)Show the steps and the answer
It displays 11.
Why: 3 and 8 are added to the total. The 0 matches the test, so break ends the loop before 0 would be added, and the 5 is never read.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.4 break and continue Statements
Sources
- Python 3.13 Tutorial, 4.4 break and continue Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 7.9 The break statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.3 The for statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.2 The while statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: input. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: KeyboardInterrupt. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: int. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.