Choosing with if and else
So far, every program you have written runs each of its lines once, from top to bottom. That is enough for a calculation, but most programs also need to do two other things.
Sometimes a program has to choose. Say a cinema charges 1,800 yen for a ticket and 900 yen for a child under 12, and you want a program that reads someone's age and prints their price. When you write the program, you don't know what age will be typed. So the program has to hold both prices and print the right one when it runs.
Sometimes a program has to repeat. If you want the total of the numbers from 1 to 1,000, you don't want to write out a thousand additions. You want to write one addition and have it run a thousand times.
The statements that decide which lines run next, and how many times, are called control statements. In this lesson we'll learn three of them:
if, which chooses which lines to runwhile, which repeats lines for as long as a condition is truefor, which repeats lines once for each number in a range
Here is the cinema program:
age = int(input())
if age < 12:
print(900)
else:
print(1800)Type 8 and the program prints 900; type 30 and it prints 1800. The expression age < 12 is called the condition. It is either true or false, and you build it with comparisons such as < and ==. An if statement works out its condition and runs the lines under it only when the condition is true. When the condition is false, the lines under else run instead. So whatever age you type, exactly one of the two prices gets printed.
The lines an if controls are called its body, just like a function's body. You write them the same way too: the if line ends with a colon, and the body is indented below it. else works the same way.
You now know enough to solve your first problem with if. Product, the first problem in this lesson's list, is practice for exactly this.
You are given two positive integers and , and you print whether their product is even or odd. For 3 4 the product is 12, so the answer is Even; for 1 21 it is 21, so the answer is Odd. A number is even when dividing it by 2 leaves remainder 0, so the condition your if checks is a * b % 2 == 0.
More than two choices
Now suppose children under 6 get in free. That makes three prices, but if and else only give you two places to put lines. For the third, you add elif, short for "else if", which checks another condition in between:
age = int(input())
if age < 6:
print(0)
elif age < 12:
print(900)
else:
print(1800)The program checks the conditions from the top down and runs the body of the first one that is true. Everything after that is skipped. Take a 4-year-old: age < 6 is true, so the program prints 0 and doesn't even look at age < 12, although that is true too. For an 8-year-old, age < 6 is false, so the program moves on to age < 12, which is true, and prints 900. The else body runs only when every condition above it was false.
This means the order of your checks matters. If you put age < 12 first, a 4-year-old would stop there and pay 900, and the free price could never be printed. When one condition is narrower than another, check the narrow one first.
Where an if body ends
Since an if runs its body only when the condition is true, you need to know exactly which lines are in the body. Let's say the cinema program should also print Child ticket for children. Here is that program, run for a 30-year-old:
age = 30
price = 1800
if age < 12:
price = 900
print("Child ticket")
print(price)It prints 1800. Python works out where the body ends by looking at the indentation. The body is every line indented further than the if. The first line back at the same level as the if, here print(price), is no longer part of the body. So for a 30-year-old both body lines are skipped, and print(price) runs whatever the age.
Because Python reads the structure from your indentation, the indentation has to be consistent. If a line is indented to a level that doesn't match any block above it, Python won't run the program at all and reports an IndentationError. Mixing tabs and spaces in one block gives a TabError. Use 4 spaces for each level.
Two tests in one condition
Sometimes one comparison isn't enough. You can join comparisons with and, or and not, and with and the order of the two sides can decide whether your program crashes. Say a student passes a course when the average of their test scores is at least 60. You get the average by dividing their total by count, the number of tests. But a student who hasn't taken any tests yet has a count of 0, and dividing by 0 is an error.
total = 0
count = 0
if count > 0 and total / count >= 60:
print("pass")
else:
print("no pass yet")The program prints no pass yet and doesn't crash. and skips its right side when its left side is false, since the whole condition is false either way. Here count > 0 is false, so total / count never gets worked out. If you write the two sides the other way round, total / count >= 60 and count > 0, the division happens first and the program stops with ZeroDivisionError. Put the test that rules out the error on the left of and.
Deeper read: a number as a condition
A condition does not have to be a comparison. When it is a number, 0 counts as false and every other number as true, so if count: means the same as if count != 0:. An empty string "" also counts as false, and a string with at least one character counts as true. You will see this short form in other people's code.
Repeating with while
An if body runs once or not at all. To run lines over and over, you need a loop. The simplest one is the while loop. It checks its condition, and if the condition is true it runs its body, then goes back and checks again. As soon as the condition is false, the loop stops and the program carries on below it. Each pass through the body is called an iteration.
A while line ends with a colon and its body is indented, as with if.
Here is a program that counts how many times you can halve 40 before you get an odd number. Notice that the answer, 3, isn't written anywhere in the code. The loop finds it while the program runs, by checking the condition again after every halving. Step through it in the diagram below, and watch the next-line marker jump back up to the while line after each pass.
Step through a loop
| Check | n | n % 2 == 0 | steps after the pass |
|---|---|---|---|
| 1 | 40 | true | 1 |
| 2 | 20 | true | 2 |
| 3 | 10 | true | 3 |
| 4 | 5 | false | the loop ends with 3 |
The condition is checked four times and is true three times. On the fourth check n is 5 and 5 % 2 is 1, so the condition is false and the program moves on to the line after the loop.
Try the other starting values in the diagram too. They show the edge cases. With n = 7 the very first check is false, so the body does not run at all and steps stays 0: a loop can run zero times. With n = 96 the loop halves five times, through 48, 24, 12 and 6 down to 3. With n = 0, halving gives 0 again, so the condition is true on every check and the loop does not end.
Deeper read: loops that never end
A while loop ends only when its condition becomes false, so its body has to change something the condition reads. Without the line that halves n, the halving loop would check 40 forever.
On your own computer, Ctrl+C stops such a program. On a judge it keeps running until the time limit, often 1 or 2 seconds, and gets a Time Limit Exceeded verdict.
Counting with for
The halving loop couldn't know in advance how many passes it would need. But many loops do know. Adding up the numbers from 1 to takes exactly passes, one for each number. You can already write this with while, using a counter i that you set up, check and move along yourself:
n = int(input())
total = 0
i = 1
while i <= n:
total += i
i += 1
print(total)It works, but three separate lines look after the counter: i = 1 before the loop, the condition i <= n, and i += 1 at the end of the body. If you forget the last one, i stays 1 and the loop never ends. Counting through a range of numbers comes up so often that both languages give you a loop that keeps the counter for you. A for loop gives a loop variable each value in a range, one value per iteration.
The same sum with for
n = int(input())
total = 0
for i in range(1, n + 1):
total += i
print(total)Python details
range(1, n + 1) gives 1, 2, …, n. It starts at its first number and stops just before its second, which is why the second number is n + 1.
Given 1000, this version prints 500500 too. Its body runs once with i equal to 1, once with 2, and so on up to 1000, and each pass adds i to total. If you want to check the answer, the sum has a formula:
Leaving a loop early with break and continue
Sometimes a loop finds what it was looking for before its last iteration, and there is no point carrying on. Say you want the smallest number above 1 that divides 91. You can try 2, 3, 4 and so on, and stop at the first one that divides:
n = 91
for d in range(2, n + 1):
if n % d == 0:
break
print(d)break ends the loop at once, and the program carries on after it. Here the loop tries 2 to 6, finds that 7 divides , and stops after six iterations instead of 90.
continue is the milder version: it skips the rest of the current iteration and goes on to the next one. In a loop over 1 to 10 whose body begins with if i % 3 == 0: continue, the rest of the body runs for every number except 3, 6 and 9.
Notice that the program prints d after the loop has finished. A Python loop variable keeps its last value once the loop ends, so d is still 7.
Putting loops and choices together
The body of an if, a while or a for can hold any statements you like. That includes other if statements and other loops. Some Sums, the second problem in this lesson's list, uses all three, so it is a good one to work through together.
You are given , at most 10,000, and two numbers and . You have to print the total of the numbers from 1 to whose digits add up to a value between and . In the sample 20 2 5, the numbers from 1 to 20 with a digit sum between 2 and 5 are 2 to 5, 11 to 14, and 20. The rest have a digit sum of 1, as 1 and 10 do, or above 5, as 6 and 19 do. Adding up the nine numbers gives the answer:
The program can follow the statement step by step. A for loop visits every number from 1 to . Inside it, an if adds the number to the answer when its digit sum is between and . Working out the digit sum takes a loop of its own, a while, because you don't know in advance how many digits a number has. x % 10 gives you the last digit of x, and x // 10 drops it, so the loop keeps adding the last digit and dropping it until nothing is left. We need the digit sum of every number, so it goes in a function.
def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x //= 10
return total
n, a, b = map(int, input().split())
answer = 0
for i in range(1, n + 1):
if a <= digit_sum(i) <= b:
answer += i
print(answer)Python details
a <= digit_sum(i) <= b is a chained comparison: it means a <= digit_sum(i) and digit_sum(i) <= b, with digit_sum(i) worked out once.
For 14, the first pass of the while loop adds 4 and leaves 1, and the second adds 1 and leaves 0, so the digit sum is 5. That is between 2 and 5, so the if adds 14 to the answer.
Testing digit_sum
Before you submit, it is worth testing digit_sum on its own, with one assert for each kind of input. A function with a loop inside has its own kinds of input to try:
- one where the loop body runs zero times
- one where it runs once
- one where it runs several times
Here are tests of each kind for digit_sum, plus one more for a number with zeros in it.
def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x //= 10
return total
assert digit_sum(0) == 0
assert digit_sum(7) == 7
assert digit_sum(14) == 5
assert digit_sum(10000) == 1
print("all tests passed")With 0 the condition x > 0 is false at the first check, so the body runs zero times and total stays 0. With 7 the body runs once, and with 14 twice. 10000 runs the body five times and passes four zero digits on the way.
The last test is there to catch an easy mistake: writing the condition as while x % 10 > 0, which reads as "while the last digit is not zero". A loop written that way passes the first three tests. For 10000 it stops at the first zero digit and returns 0, so the fourth assert fails.
Common mistakes
Writing
=where you mean==.- Where it breaks
- In Python,
if age = 5:is aSyntaxError. In C++,if (age = 5)compiles: it stores 5 inage, and the condition is always true. - The fix
- Use
==to compare and=to store.
Checking a wide condition before a narrow one.
- Where it breaks
- With
age < 12checked beforeage < 6, a 4-year-old pays 900 instead of 0, and the free price is never printed. - The fix
- Put the narrower condition first.
Indenting a line to look like part of an
ifbody.- Where it breaks
- In C++, the indented
cout << "Child ticket\n";underif (age < 12) price = 900;with no braces runs for every age, so a 30-year-old is told it is a child ticket. In Python, a line at a level that matches no block above it is anIndentationError. - The fix
- In C++, put braces around every body. In Python, use 4 spaces per level and no tabs.
Putting the risky test on the left of
and.- Where it breaks
- With
count = 0,total / count >= 60 and count > 0divides by zero first: Python stops withZeroDivisionError, and in C++ the result is undefined. - The fix
- Write the guard first,
count > 0 and total / count >= 60, soandstops before the division.
Stopping one short with
range.- Where it breaks
range(1, n)gives 1 to n − 1, so Some Sums never visits 20 and prints 64 for20 2 5instead of 84.- The fix
- Write
range(1, n + 1)to include n; in C++, loop whilei <= n.
Writing
a <= s <= bin C++.- Where it breaks
- It compiles, but it compares the result of
a <= s(1 or 0) withb, so every number counts and Some Sums prints 210 for20 2 5. - The fix
- Write
a <= s && s <= b.
Never changing what a
whilecondition reads.- Where it breaks
- Delete the line that halves
nand start the loop at 40:nstays 40, and the program runs until it is stopped or a judge reports Time Limit Exceeded. - The fix
- Check that each iteration moves the loop toward a false condition.
Recall If the cinema program checked `age < 12` before `age < 6`, what would a 4-year-old pay?
900. The checks run from the top and stop at the first true one. age < 12 is true for 4, so the program prints 900 and never reaches age < 6.
Recall Starting the halving loop with `n = 12`, how many times is the condition checked, and what is `steps` at the end?
Three checks: 12 and 6 are even, and 3 is odd. The body runs twice, so steps ends at 2.
Key terms
| Term | Meaning |
|---|---|
| control statement | A statement that decides which statements run and how many times: if, while, for. |
| condition | The true-or-false expression an if statement or a loop checks. |
| if statement | Runs its body only when its condition is true; else gives the body for the other case. |
| loop | A statement that runs its body again and again. |
| iteration | One pass through a loop's body. |
| for loop | A loop that gives its loop variable each value in a range. |
| loop variable | The name that holds the current value in a for loop, such as i. |
