Choosing and repeating
The programs in the last lesson ran straight from top to bottom, every line exactly once. That is enough for a calculator, but almost nothing else. Think about what real programs do:
- A ticket machine checks whether your card has enough money. If it does, it opens the gate; otherwise it beeps and shows a message.
- A teacher's register app goes through the class list and, for each student, records present or absent.
- A phone's alarm checks the time, again and again, until it is 6:30, and then rings.
These need the other two building blocks of algorithms from the first lesson: choice and repetition. With them, a ten-line program can process a million records, and the same program can behave sensibly in situations its author never listed one by one. This lesson teaches both, and then a skill that every programmer uses daily: tracing a program by hand to see exactly what it does.
Pictures of choice and repetition
Before any Python, here are the two shapes as flowcharts. A diamond is a question with a yes-or-no answer; a box is an action.
Both shapes hang on a condition: a question whose answer is True or False. So we start with conditions.
Conditions, blocks and loops
Definition— condition
A condition (or Boolean expression) is an expression whose value is True or False, such as age >= 18 or balance < fare.
Python's comparison operators are:
| Operator | Meaning | Example that is True |
|---|---|---|
== | equal to | 2 + 2 == 4 |
!= | not equal to | "cat" != "dog" |
<, <= | less than, less than or equal to | 3 <= 3 |
>, >= | greater than, greater than or equal to | 10 > 9 |
Python also lets you chain comparisons as in maths: 0 <= mark <= 100 means "mark is between 0 and 100, inclusive".
Definition— and, or, not
A and B is True only when both A and B are True. A or B is True when at least one of them is True. not A is True exactly when A is False.
A | B | A and B | A or B | not A |
|---|---|---|---|---|
True | True | True | True | False |
True | False | False | True | False |
False | True | False | True | True |
False | False | False | False | True |
This is the same logic as in Lumenary Math's True, false, and, or, not. Note that or in programming is inclusive: "tea or coffee?" answered with "both" is True.
Python evaluates and and or from left to right and stops as soon as it knows the answer. This is called short-circuit evaluation, and it is useful as a guard: in count > 0 and total / count > 50, the division is only attempted when count > 0 is True, so it can never divide by zero.
Note
In a condition, Python treats a few values as false even though they are not False itself: the number 0, the float 0.0, the empty string "", and empty collections (which you'll meet in Lists, strings and dictionaries). Everything else counts as true. Programmers call this truthiness. It is handy (if name: means "if the name is not empty"), but it is also behind one of the classic bugs in the misconceptions below.
Definition— block
A block is a group of lines indented by the same amount (Python programmers use four spaces) under a line ending with a colon :. The block belongs to that line: it is what gets done if the condition holds, or what gets repeated.
Definition— loop
A loop repeats a block. A while loop repeats it as long as a condition stays True. A for loop repeats it once for each item in a sequence, such as the numbers produced by range. Each pass through the block is called an iteration.
Making decisions
The simplest decision is an if with a block:
if balance < fare:
print("Not enough money on this card.")Add else for what to do otherwise, and elif (short for "else if") for more than two cases. Python checks the conditions from top to bottom and runs the block of the first one that is True, skipping all the rest.
Example— Ticket prices at a museum
A museum in Cusco charges nothing for children under 5, 10 soles for anyone under 18, 15 for adults, and 8 for people aged 65 and over.
if age < 5:
price = 0
elif age < 18:
price = 10
elif age >= 65:
price = 8
else:
price = 15Because Python stops at the first true condition, the second test age < 18 only ever sees people who are at least 5, so it really means "from 5 to 17". The order of the tests is part of the algorithm. If you put a test age >= 18 before the senior test, a 70-year-old would match it first and pay the adult price.
Example— Is it a leap year?
In the Gregorian calendar, a year is a leap year if it is divisible by 4, except that years divisible by 100 are not, except that years divisible by 400 are. So 2024 is a leap year, 1900 was not, and 2000 was. Using % from the last lesson, "divisible by 4" is year % 4 == 0, and the whole rule fits in one condition:
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0The parentheses matter: and is done before or (just as * before +), but writing them makes the meaning obvious.
Change age and year below and predict the output before each run.
age = 70
if age < 5:
price = 0
elif age < 18:
price = 10
elif age >= 65:
price = 8
else:
price = 15
print(f"Age {age}: {price} soles")
year = 1900
is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
if is_leap:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
mark = 73
print("valid mark:", 0 <= mark <= 100)
print("merit band (60 to 79):", mark >= 60 and mark < 80)
print("not a fail:", not mark < 50)Repeating with while
A while loop is an if that keeps coming back. Python checks the condition; if it is True, it runs the block and then checks again; when the condition is False, it continues after the loop.
Example— How long until the town doubles?
A town of 50 000 people grows by 3% a year. How many years until it has more than 100 000? We don't know in advance how many times to repeat "one more year", so a while loop is the natural fit:
population = 50000
years = 0
while population <= 100000:
population = population * 1.03
years = years + 1Each iteration moves one year forward. Something in the block must eventually make the condition False; here population grows each time. If you forgot the line that grows it, the condition would stay True for ever: an infinite loop. (If that ever happens in a Run box, reload the page.)
population = 50000
years = 0
while population <= 100000:
population = population * 1.03
years += 1
print(f"After {years} years: about {population:.0f} people")
# Counting down
n = 5
while n > 0:
print(n, end=" ")
n -= 1
print("Lift-off!")The end=" " inside print tells it to finish with a space instead of starting a new line, so the countdown appears on one line.
while or for?
Both loops can do the same jobs, so how do you choose? A good rule of thumb:
- Use
forwhen you know in advance what you are going through: the numbers 1 to 100, every year from 1900 to 2100, every student on a list. The loop takes care of moving on, so it can't accidentally run for ever. - Use
whilewhen you only know the condition for stopping: "until the population doubles", "until the user types quit", "until the number reaches 1".
When in doubt, prefer for. It says more clearly what the loop is for, and there is no update line to forget.
Repeating with for, and accumulators
When you know what you want to go through, such as "every number from 1 to 100", a for loop is simpler. The built-in range produces a sequence of whole numbers:
| Code | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 20, 5) | 0, 5, 10, 15 |
range(10, 0, -3) | 10, 7, 4, 1 |
The rule: range(start, stop, step) starts at start, goes up (or down) by step, and stops before reaching stop. Leaving out start means 0, and leaving out step means 1. A useful consequence: range(n) has exactly n numbers.
for i in range(1, 6):
print(i, "squared is", i * i)The variable i (the loop variable) takes each value in turn: 1 on the first iteration, 2 on the second, and so on.
The accumulator pattern
Many loops build up an answer bit by bit in a variable called an accumulator. You set it up before the loop, update it inside the loop, and use it after the loop:
total = 0 # before: nothing added yet
for n in range(1, 101):
total += n # inside: add one more number
print(total) # after: 5050There is a famous story, possibly polished in the retelling, that the young Carl Friedrich Gauss found this sum in moments by pairing 1 with 100, 2 with 99 and so on: fifty pairs, each adding to 101. The loop does it the slow way, but it works for any list of numbers, not only neat ones.
The same pattern counts things (start at 0, add 1 when something is true), multiplies (start at 1) and tracks a best value so far:
total = 0
for n in range(1, 101):
total += n
print("1 + 2 + ... + 100 =", total)
count = 0
for n in range(1, 101):
if n % 7 == 0:
count += 1
print("Multiples of 7 up to 100:", count)
product = 1
for n in range(1, 11):
product *= n
print("1 x 2 x ... x 10 =", product)
# Which whole number x from 0 to 20 makes x * (20 - x) largest?
best_x = 0
best_value = 0
for x in range(21):
value = x * (20 - x)
if value > best_value:
best_value = value
best_x = x
print("Best x:", best_x, "giving", best_value)Loops inside loops, break and continue
A loop's block can contain another loop. The inner loop then runs completely, from start to finish, on every iteration of the outer loop. This is how you go through all pairs of things, such as every cell of a multiplication table.
Example— Paying with coins
In how many ways can you pay exactly 20 using coins worth 2 and 5? Let fives run over every possible number of 5-coins and twos over every possible number of 2-coins, and count the pairs that make 20:
ways = 0
for fives in range(0, 5): # 0 to 4 coins of 5
for twos in range(0, 11): # 0 to 10 coins of 2
if 5 * fives + 2 * twos == 20:
ways += 1The inner if runs 5 × 11 = 55 times in all, and finds 3 ways: ten 2s; two 5s and five 2s; four 5s.
Two more keywords give you finer control inside any loop:
breakleaves the loop immediately, skipping any remaining iterations.continueskips the rest of the current iteration and goes straight on to the next one.
The program below uses break to test whether numbers are prime (divisible only by 1 and themselves): it searches for a divisor and stops as soon as it finds one, because one divisor is enough to know the answer.
for row in range(1, 6):
for col in range(1, 6):
print(f"{row * col:3}", end="")
print() # finish the row
print()
primes_found = 0
for n in range(2, 50):
is_prime = True
for d in range(2, n):
if d * d > n:
break # no divisor up to the square root: stop looking
if n % d == 0:
is_prime = False
break # found a divisor: n is not prime
if is_prime:
primes_found += 1
print(n, end=" ")
print()
print(primes_found, "primes below 50")Why stop at the square root? If with both factors bigger than , their product would be bigger than . So if has a divisor other than 1 and itself, it has one no bigger than , and checking d * d > n lets the loop quit early. That one line makes the test much faster for big numbers, an idea you will measure properly in Measuring the cost of a program.
Tracing a loop by hand
When a loop does something unexpected, the most reliable thing to do is to trace it: play the computer, line by line, and write down the variables after each iteration in a table. It feels slow, but it is how you find out what the code really does, rather than what you hoped it does.
Here is a loop that adds up the digits of a number:
n = 472
total = 0
while n > 0:
digit = n % 10
total += digit
n = n // 10| Iteration | n at start | digit | total after | n after |
|---|---|---|---|---|
| 1 | 472 | 2 | 2 | 47 |
| 2 | 47 | 7 | 9 | 4 |
| 3 | 4 | 4 | 13 | 0 |
After the third iteration n is 0, the condition n > 0 is False, and the loop ends with total equal to 13, which is indeed 4 + 7 + 2. The table also shows why the loop must end: n gets smaller every time and can't go below 0.
Some loops are much harder to reason about. Start with any positive whole number; if it is even, halve it; if it is odd, multiply by 3 and add 1; repeat until you reach 1. Starting from 6, you get 6, 3, 10, 5, 16, 8, 4, 2, 1. Does this process reach 1 for every starting number? Nobody knows! It is called the Collatz problem, after Lothar Collatz, who posed it in the 1930s; it has been checked by computer for enormous ranges of numbers, but it has never been proved. A four-line loop can hide an unsolved problem in mathematics.
To check your hand traces, try Python Tutor, which steps through a program and shows every variable as it changes.
Common mistakes
Misconception
if x = 5: A single = is assignment, and Python reports a SyntaxError here. To compare, use ==.
Misconception
if colour == "red" or "blue": This reads naturally in English but means (colour == "red") or ("blue"), and a non-empty string counts as true in a condition, so the test is always true. Write each comparison in full: colour == "red" or colour == "blue".
Misconception
"range(1, 10) goes up to 10." It stops before 10, so it gives 1 to 9. This kind of slip, being out by one at the start or end of a loop, is so common that it has a name: an off-by-one error.
Misconception
"A while loop moves on by itself, like a for loop." A for loop moves its variable on by itself; a while loop does not. If nothing in the block changes the condition, the loop runs for ever.
Misconception
Indentation is just for looks. In Python, indentation is the structure: it decides which lines belong to the if or the loop. Moving a line four spaces left or right can change what the program does without any error message.
Exercises
For the tracing questions, make a table on paper before you answer. Then check yourself by running the code.
1. Decisions and loops
Warm-upComputationalWhat does this program print?
day = "Tuesday"
if day == "Saturday" or "Sunday":
print("Weekend!")
else:
print("School day")
2. Decisions and loops
Warm-upComputationalHow many times does the body of this loop run?
for i in range(3, 20, 4):
print(i)
3. Decisions and loops
CoreComputationalTrace this loop by hand. What does it print?
total = 0
for i in range(1, 6):
if i % 2 == 0:
continue
total += i * i
print(total)
4. Decisions and loops
CoreHumanA shop gives a discount unless the customer is both under 18 and without a student card. Which condition is always equal to not (under_18 and no_card)?
5. Decisions and loops
CoreComputationalThis program is meant to charge 0 for under-5s, 10 for under-18s, 8 for people 65 and over, and 15 for other adults. For which age does it give the wrong price?
if age < 5:
price = 0
elif age < 18:
price = 10
elif age >= 18:
price = 15
elif age >= 65:
price = 8
6. Decisions and loops
CoreComputationalWrite a while loop that sets digit_total to the sum of the digits of n. The starter sets n to , a 31-digit number, so working it out by hand is not much fun! Use % 10 to get the last digit and // 10 to remove it, as in the lesson.
7. Decisions and loops
CoreComputationalUse a for loop over range and the leap-year rule from the lesson to set leap_count to the number of leap years from 1900 to 2100, including both. Remember: divisible by 4, except years divisible by 100, except years divisible by 400.
8. Decisions and loops
StretchComputationalIn how many different ways can you pay exactly 100 using any number of coins worth 1, 2 and 5? (Only the number of each coin matters, not their order.)
Use nested loops to set ways. One approach: loop over the number of 5-coins and the number of 2-coins; for each pair, the 1-coins must make up the rest, so check whether the rest is not negative.
Further reading and resources
- The Python Tutorial: More control flow tools · Python Software Foundationif, for, range, break and continue, with examples.
- Boolean operations: and, or, not · Python Software Foundation
- Python Tutor · Philip GuoPaste in a short program and step through it line by line, watching every variable change. An excellent way to check a hand trace.