Objectives: LO-3.1, LO-3.2, LO-3.3
Prerequisites: Module 2
Time: about 5.5 hours: 2 for this reading, 2 for Lab 3, and 1.5 for the
practice
Every program so far has run each of its lines once, from top to bottom. Real programs choose: a ticket machine charges a child less than an adult, and a login page lets in only the right password. In this module you learn to ask questions whose answer is true or false, to combine them, and to make a program run different code depending on the answer. You also learn to test a decision, because a program that chooses has more ways to go wrong.
Comparisons¶
Module 2 introduced the two Boolean values, True and False. A comparison asks a question
about two values and answers with one of them:
| Operator | Question | Example | Value |
|---|---|---|---|
== | Equal? | 7 == 7 | True |
!= | Not equal? | 7 != 7 | False |
< | Less than? | 3 < 5 | True |
> | Greater than? | 3 > 5 | False |
<= | Less than or equal? | 5 <= 5 | True |
>= | Greater than or equal? | 4 >= 5 | False |
A Boolean value can be stored like any other: is_adult = age >= 18 makes is_adult refer to
True or False.
= and == are different¶
= makes a name refer to a value, and == asks whether two values are equal. Writing = where
you meant == is a syntax error, and Python suggests the fix:
x = 5
if x = 5:
print("five") File "/home/you/py101/five.py", line 2
if x = 5:
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?(:= is a different operator, which this course doesn’t use.)
Comparing numbers and strings¶
Numbers compare by value, whatever their type: 10 == 10.0 is True. Floats are approximate, so
Module 2’s warning holds here too: 0.1 + 0.2 == 0.3 is False, and math.isclose is the way
to compare them.
Strings compare one character at a time, from the left, until two characters differ. Each
character has a number, its code point, and the character with the smaller number comes first.
Letters are numbered in alphabetical order, so "apple" < "banana" is True, and
"cab" < "cat" is True because b comes before t. Two results surprise people:
Every capital letter comes before every lowercase letter (
Ais 65,Zis 90, andais 97), so"Zebra" < "apple"isTrue.Digits in a string are characters, not numbers, so
"10" < "9"isTrue: the first characters differ, and1comes before9.
A string is never equal to a number: "10" == 10 is False, which is one more reason to convert
input. Asking which is smaller is an error: "10" < 10 stops with
TypeError: '<' not supported between instances of 'str' and 'int'.
Chained comparisons¶
To ask whether a value lies in a range, chain two comparisons: 0 <= score <= 100 is True when
score is between 0 and 100, inclusive. It means the same as 0 <= score and score <= 100, the
form you will see in many other languages.
Combining conditions: and, or, and not¶
Three logical operators combine Boolean values:
a and bisTrueonly when both areTrue.a or bisTruewhen at least one isTrue.not aisTruewhenaisFalse, and the other way around.
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 |
or means “one or the other, or both”. Everyday English often means “one or the other, but not
both”, as in “soup or salad”; Python’s or never does.
Which goes first¶
Arithmetic runs first, then comparisons, then not, then and, then or. So
age >= 13 and age < 65 or is_membermeans ((age >= 13) and (age < 65)) or is_member. As with arithmetic, parentheses make your
meaning plain and cost nothing.
Worked example: checking before dividing¶
and and or stop as soon as they know the answer, which is called short-circuit
evaluation. When the left side of and is False, the whole expression is False, so Python
never evaluates the right side. That makes this safe:
count = 0
print(count != 0 and 100 / count > 10)Falsecount != 0 is False, so Python stops there and never divides by zero, which would stop the
program with a ZeroDivisionError. Swap the two sides, 100 / count > 10 and count != 0, and the
division runs first and fails. In the same way, or stops when its left side is True.
Which values count as false¶
if and the logical operators accept any value, not only True and False. Python treats a few
values as false, and every other value as true:
FalseandNone(Noneis Python’s value for “nothing”; Module 5 shows where it comes from);zero:
0and0.0;the empty string,
"";empty collections, such as the empty list, which Module 7 introduces.
bool shows how Python treats a value: bool(0) is False, and bool(-1) is True. Values
that count as false are often called falsy, and the rest truthy. A few truthy strings
catch people out: "0", " " (a single space), and "False" all count as true, because only the
empty string is false.
The or mistake¶
This program is meant to continue only when the user types yes or y:
answer = input("Continue? ")
if answer == "yes" or "y":
print("Continuing")It continues whatever the user types, even no. The condition means
(answer == "yes") or ("y"): when the left side is False, or gives back its right side, the
string "y", and a non-empty string counts as true. English lets “is yes or y” share the “is”;
Python doesn’t. Each comparison must be complete:
if answer == "yes" or answer == "y":if statements¶
An if statement runs a block of code only when a condition is true:
temperature = 31
if temperature >= 30:
print("It's hot.")
print("Drink plenty of water.")
print("Have a good day.")It's hot.
Drink plenty of water.
Have a good day.The first line is the word
if, a condition, and a colon (:).The lines after it that are indented, moved right by four spaces, form its block: the code that runs only when the condition is true.
The first line that isn’t indented ends the block.
Have a good day.prints whatever the temperature.
Change temperature to 25, and only Have a good day. prints.
Python uses the indentation itself to decide which lines belong to the block, so the spaces matter. Use four spaces for each level; VS Code and JupyterLab insert four when you press Tab after a colon, and the Python style guide, PEP 8, recommends four.
Indentation errors¶
| The mistake | The message’s last line |
|---|---|
| Nothing indented after the colon | IndentationError: expected an indented block after 'if' statement on line 2 |
A line indented less than the block, but more than the if | IndentationError: unindent does not match any outer indentation level |
| A line indented when nothing above it ends in a colon | IndentationError: unexpected indent |
| The colon missing after the condition | SyntaxError: expected ':' |
All four are syntax errors: Python reports them before it runs any line, as Module 1 described.
else and elif¶
Two cases: else¶
else gives a block to run when the condition is false. Exactly one of the two blocks runs.
number = int(input("A whole number: "))
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")number % 2 is the remainder after dividing by 2, which is 0 for every even number, negative
ones included.
Several cases: elif¶
elif, short for “else if”, adds more conditions. Python checks the conditions from the top
down, runs the block of the first one that is true, and skips the rest. else, if present,
runs when none of them is true.
Worked example: describing a temperature¶
A weather app describes 30 degrees and above as hot, 20 to 29 as warm, 10 to 19 as mild, and anything colder as cold.
temperature = 24
if temperature >= 30:
print("hot")
elif temperature >= 20:
print("warm")
elif temperature >= 10:
print("mild")
else:
print("cold")For 24, the first condition is false, and the second is true, so it prints warm, and Python
skips the rest. The third condition, 24 >= 10, is also true, but Python never asks it. The order
of the conditions is what makes this work: the second condition doesn’t need to say “and below
30”, because a temperature of 30 or more never gets past the first.
The order of the conditions matters¶
Put the same conditions in the opposite order, and the program goes wrong without any error:
temperature = 35
if temperature >= 10:
print("mild")
elif temperature >= 20:
print("warm")
elif temperature >= 30:
print("hot")
else:
print("cold")It prints mild for 35, because 35 >= 10 is true and Python looks no further. Every
temperature of 10 or more stops at the first condition, so the warm and hot blocks can never
run: they are unreachable. When conditions overlap, check the narrowest one first. Here, with
>=, that means the highest threshold first; with <, the lowest first.
if without elif¶
A chain of if, elif, and else runs at most one block. A run of separate if statements
checks every condition, and may run several blocks:
temperature = 35
if temperature >= 30:
print("hot")
if temperature >= 20:
print("warm")This prints both hot and warm. Use elif when the cases exclude each other, and separate if
statements when each check is independent, such as warning about heat and, separately, about
wind.
Decisions inside decisions¶
A block can hold another if, indented one more level:
age = 16
has_ticket = True
if has_ticket:
if age >= 18:
print("Enjoy the film.")
else:
print("Enjoy the film. Under-18s sit in the front rows.")
else:
print("Please buy a ticket first.")Nesting suits a second question that only makes sense after the first. When both questions must
be true for one action, and is usually clearer: if has_ticket and age >= 18: needs one level,
not two. Deep nesting is hard to read, so prefer the flatter form when it says the same thing.
Testing a decision¶
A program that chooses has a path through each branch, and a mistake can hide in any of them. To test a decision, run it with inputs chosen to find mistakes, and compare each result with the answer you worked out by hand. Two rules choose the inputs:
Reach every branch. Choose at least one input for each block, so that every line runs at least once.
Test both sides of every boundary. A boundary is where the answer changes. Most mistakes in decisions are off by one there:
<written where<=was meant, or 65 where the rule said 64. Test the last value on each side.
Worked example: choosing the tests¶
A car park charges nothing for the first 30 minutes, 2.00 up to 120 minutes, and 5.00 after that.
if minutes <= 30:
fee = 0.00
elif minutes <= 120:
fee = 2.00
else:
fee = 5.00The answer changes between 30 and 31 minutes and between 120 and 121. The tests are:
| Minutes | Why | Expected fee |
|---|---|---|
| 0 | The smallest input | 0.00 |
| 30 | Last minute that is free | 0.00 |
| 31 | First minute that is charged | 2.00 |
| 120 | Last minute at 2.00 | 2.00 |
| 121 | First minute at 5.00 | 5.00 |
| 300 | Well inside the last band | 5.00 |
Six tests reach every branch and sit on each side of both boundaries. If someone had written
minutes < 30, the test with 30 would catch it; no test inside a band would.
Checking a result with assert¶
An assert statement checks that something is true:
assert fee == 2.00, "31 minutes is past the free half hour"When the condition is true, assert does nothing, and the program carries on. When it is false,
assert stops the program with an AssertionError and the message after the comma:
AssertionError: 31 minutes is past the free half hourThat’s what Lab 1’s and Lab 2’s check cells do. To test the car park’s decision, set minutes,
run the decision, and assert the fee you expect:
minutes = 31
if minutes <= 30:
fee = 0.00
elif minutes <= 120:
fee = 2.00
else:
fee = 5.00
assert fee == 2.00, "31 minutes is past the free half hour"
print("passed")Then change minutes and the expected fee for each row of the table, and run it again. That’s
slow, and Module 5 makes it one line per test. Lab 3 gives you a helper that runs a script with
each input, so each test is one assert.
Comparing fee == 2.00 is safe here because both sides are the same exact value, typed the same
way. For a fee that the program calculates, use math.isclose.
Common misconceptions¶
| Belief | What Python does | Example that breaks it |
|---|---|---|
= and == mean the same | = assigns, and == compares | if x = 5: is a SyntaxError |
answer == "yes" or "y" checks for either word | It means (answer == "yes") or "y", which is always truthy | Typing no still continues |
Only False counts as false | None, 0, 0.0, "", and empty collections do too | if 0: never runs its block |
"0" and "False" count as false | Only the empty string is a false string | bool("0") is True |
| Strings compare like the numbers they hold | They compare character by character | "10" < "9" is True |
Every true condition in an if-elif chain runs its block | Only the first true one does | The wrong-order temperature chain prints mild for 35 |
Separate if statements behave like elif | Each is checked, and several may run | 35 prints both hot and warm |
| Testing one value in each branch is enough | Mistakes cluster at the boundaries | minutes < 30 passes the tests 10, 60, and 300 |
or means one or the other, not both | It is true when both are | True or True is True |
Summary¶
Comparisons (
==,!=,<,>,<=,>=) giveTrueorFalse. Strings compare character by character, with capitals first and digits as characters.and,or, andnotcombine conditions; they run after comparisons, in that order, and stop as soon as they know the answer.None, zero, the empty string, and empty collections count as false, and every other value counts as true.ifruns an indented block when its condition is true;elseruns when it is false;elifadds cases, and only the first true one runs. Order overlapping conditions from the narrowest.Test a decision with an input in every branch and on both sides of every boundary, and check each result with
assert.
Self-check¶
Answer each question before you open its answer.
What are the values of
5 > 3 and 3 > 5,not 5 > 3 or 3 > 5, and2 < 3 < 1?Answer
False,False, andFalse. In the second,notapplies to5 > 3alone, givingFalse, and3 > 5isFalsetoo. The third means2 < 3 and 3 < 1.Which of these count as true:
0,"0",""," ",-2,None?Answer
"0"," ", and-2. Zero, the empty string, andNonecount as false.A program sets
sizeto"small"whenweight < 1,"medium"whenweight < 5, and"large"otherwise. In what order must theifandelifcheckweight < 1andweight < 5, and why?Answer
weight < 1first. Every weight below 1 is also below 5, so checkingweight < 5first would catch the small weights too, and thesmallbranch could never run.Which inputs would you use to test a decision that says a score of 50 or more passes?
Answer
49 and 50, on both sides of the boundary, plus any others you need to reach every branch, such as 0 and 100. 49 should fail and 50 should pass.
Why does
if answer == "y" or "Y":accept every answer, and how do you fix it?Answer
It means
(answer == "y") or "Y". When the comparison is false,orgives back"Y", a non-empty string, which counts as true. Write the comparison in full on both sides:if answer == "y" or answer == "Y":.
Further reading¶
The Python Tutorial, section 4.1, if Statements. A short example of
if,elif, andelse, from the language’s own documentation.The Python Standard Library, Truth Value Testing and Comparisons. The exact list of values that count as false, and every comparison operator, in two short sections.
Allen B. Downey, Think Python, 3rd edition, chapter 5, Conditionals and Recursion. Its first half covers this module’s material, including nested conditions; its second half, on recursion, is for Module 11.
Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 2, if-else and Flow Control. Boolean values, comparisons, and
if,elif, andelse, with flowcharts that draw each decision.