Repeated work: crash course
about 6 min to listen5 lessons0 questions to tryUnit 4 of 6
Short view. Each lesson's rule, its steps and its trap. Switch to Full for a worked example and a question to try in every lesson.Full view. Each lesson's rule, its steps, one worked example with Watch it solved, the trap, and one question to try.
Starts here no skill from another unit needed first
1 Read a for loop
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.
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.
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.
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.
2 Choose the bounds of range
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.
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.
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.
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.
3 Trace a while loop
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.
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.
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.
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.
4 Keep a running total
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.
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.
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
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.
5 Stop a search at a match
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.
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
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
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.