Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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:

OperatorQuestionExampleValue
==Equal?7 == 7True
!=Not equal?7 != 7False
<Less than?3 < 5True
>Greater than?3 > 5False
<=Less than or equal?5 <= 5True
>=Greater than or equal?4 >= 5False

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:

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:

aba and ba or bnot a
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

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_member

means ((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)
False

count != 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:

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.

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 mistakeThe message’s last line
Nothing indented after the colonIndentationError: expected an indented block after 'if' statement on line 2
A line indented less than the block, but more than the ifIndentationError: unindent does not match any outer indentation level
A line indented when nothing above it ends in a colonIndentationError: unexpected indent
The colon missing after the conditionSyntaxError: 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:

  1. Reach every branch. Choose at least one input for each block, so that every line runs at least once.

  2. 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.00

The answer changes between 30 and 31 minutes and between 120 and 121. The tests are:

MinutesWhyExpected fee
0The smallest input0.00
30Last minute that is free0.00
31First minute that is charged2.00
120Last minute at 2.002.00
121First minute at 5.005.00
300Well inside the last band5.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 hour

That’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

BeliefWhat Python doesExample that breaks it
= and == mean the same= assigns, and == comparesif x = 5: is a SyntaxError
answer == "yes" or "y" checks for either wordIt means (answer == "yes") or "y", which is always truthyTyping no still continues
Only False counts as falseNone, 0, 0.0, "", and empty collections do tooif 0: never runs its block
"0" and "False" count as falseOnly the empty string is a false stringbool("0") is True
Strings compare like the numbers they holdThey compare character by character"10" < "9" is True
Every true condition in an if-elif chain runs its blockOnly the first true one doesThe wrong-order temperature chain prints mild for 35
Separate if statements behave like elifEach is checked, and several may run35 prints both hot and warm
Testing one value in each branch is enoughMistakes cluster at the boundariesminutes < 30 passes the tests 10, 60, and 300
or means one or the other, not bothIt is true when both areTrue or True is True

Summary

Self-check

Answer each question before you open its answer.

  1. What are the values of 5 > 3 and 3 > 5, not 5 > 3 or 3 > 5, and 2 < 3 < 1?

    Answer

    False, False, and False. In the second, not applies to 5 > 3 alone, giving False, and 3 > 5 is False too. The third means 2 < 3 and 3 < 1.

  2. Which of these count as true: 0, "0", "", " ", -2, None?

    Answer

    "0", " ", and -2. Zero, the empty string, and None count as false.

  3. A program sets size to "small" when weight < 1, "medium" when weight < 5, and "large" otherwise. In what order must the if and elif check weight < 1 and weight < 5, and why?

    Answer

    weight < 1 first. Every weight below 1 is also below 5, so checking weight < 5 first would catch the small weights too, and the small branch could never run.

  4. 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.

  5. 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, or gives 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