Warm-up · Activity 1 of 7
// B2.1 · ~25 min · Beginner
Decisions with if, elif and else
After this lesson you can write if, elif and else chains that pick the right branch, combine conditions with and, or and not, and predict how Python treats 0, "" and None in a condition.
Lesson 1 of 5 in B2 Control flow
You will be able to
- Write if, elif and else chains, ordered so the right branch runs
- Combine comparisons with and, or and not, including chains such as 0 <= x < 10
- Predict which values count as false in a condition: None, False, zero and empty collections
Predict · Activity 2 of 7
Predict before you read on: what does this print?
temperature = 25 if temperature > 30: print("hot") elif temperature > 20: print("warm") elif temperature > 10: print("mild") else: print("cold")Practice · Activity 3 of 7
Fill in the keyword so that a score of 85 gets "B", and a score of 95 still gets only "A".
score = 95 grade = "" if score >= 90: grade += "A" ____ score >= 80: grade += "B" else: grade += "C" print(grade)score >= 80:Practice · Activity 4 of 7
or returns one of its operands. What does this print?
name = "" display = name or "guest" print(display)Practice · Activity 5 of 7
Match each expression to the value it produces.
Brain teaser · Activity 6 of 7
Brain teaser. The user typed "no". What does this print?
answer = "no" if answer == "y" or "yes": print("continuing") else: print("stopped")Apply · Activity 7 of 7
Mini-task. Write a program that reads a year with int(input()) and prints leap or common. A year is a leap year if it divides by 4, except years that divide by 100, unless they also divide by 400. Try 2000, 1900, 2024 and 2023.
Check your work against this list
Build it yourself
Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.
Worked example
Museum ticket prices
A museum charges by age: children under 6 go free, visitors under 18 and students pay 6.50 EUR, visitors of 65 or over pay 8 EUR, and everyone else pays 12 EUR. A coupon takes 2 EUR off. The program works out one visitor’s price and prints what kind of ticket it is. Change age, student and coupon at the top and run it again.
main.py
# A museum's ticket rules, checked for one visitor.
age = 16
student = False
coupon = "" # an empty string: no coupon
if age < 6:
price = 0.0
elif age < 18 or student:
price = 6.5
elif age >= 65:
price = 8.0
else:
price = 12.0
if coupon:
price = price - 2
print("Coupon used:", coupon)
if price == 0:
print("Free entry")
elif 0 < price <= 7:
print("Reduced ticket:", price, "EUR")
else:
print("Full ticket:", price, "EUR")
Run it with
python main.pyOutput
Reduced ticket: 6.5 EUR- age < 18 is already True, so Python never looks at student in age < 18 or student.
- coupon is an empty string, which is false, so the coupon block is skipped.
- 0 < price <= 7 is a chained comparison: 0 < price and price <= 7.
- The first chain puts age < 6 before age < 18: the other way round, a 4-year-old would pay 6.5.
Change it and run it
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Exercises
Exercise 1 of 2
Weather advice
The program reads a temperature in °C. Print hot above 30, warm from 21 to 30, mild from 11 to 20, and cold for 10 or less. Use one if, elif and else chain, and check the boundaries: 30 is warm, 20 is mild and 10 is cold.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
Start with the highest range: if temperature > 30. Each elif then only has to check the next boundary down.
Hint 2
"warm from 21 to 30" becomes elif temperature > 20, because anything above 30 already stopped at the first condition.
Hint 3
Four ranges need an if, two elifs and an else. The else catches everything from 10 down.
Show a solution
One way to solve it. Yours can look different and still pass the checks.
temperature = int(input())
if temperature > 30:
print("hot")
elif temperature > 20:
print("warm")
elif temperature > 10:
print("mild")
else:
print("cold")
Run it on your computer
Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.py
temperature = int(input())
# Print "hot" above 30, "warm" from 21 to 30,
# "mild" from 11 to 20 and "cold" for 10 or less.
print("cold")
test_main.py
from learnrun import run_main
def advice(temperature):
return run_main(f"{temperature}\n").strip()
def test_hot():
"""31 degrees is hot"""
got = advice(31)
assert got == "hot", f"for 31 the program printed {got!r}, expected 'hot'"
def test_warm_and_mild():
"""25 is warm and 15 is mild"""
got = advice(25), advice(15)
assert got == ("warm", "mild"), f"for 25 and 15 the program printed {got!r}, expected ('warm', 'mild')"
def test_boundaries():
"""30 is warm, 20 is mild and 10 is cold"""
got = advice(30), advice(20), advice(10)
assert got == ("warm", "mild", "cold"), f"for 30, 20 and 10 the program printed {got!r}"
def test_below_zero():
"""-5 is cold"""
got = advice(-5)
assert got == "cold", f"for -5 the program printed {got!r}, expected 'cold'"
On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.
Run the program:
python main.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyExercise 2 of 2
Sign-in check
The program reads a name and then a password, one per line. If the name is empty, print missing name. Otherwise print welcome when the password is open sesame, and wrong password when it is not. Test the empty name with not, not with == "".
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.
Hints
Hint 1
An empty string is false, so not name is True exactly when the name is empty.
Hint 2
Check the name first: the missing-name message must win even when the password is right.
Hint 3
if not name: … elif password == "open sesame": … else: …
Show a solution
One way to solve it. Yours can look different and still pass the checks.
name = input()
password = input()
if not name:
print("missing name")
elif password == "open sesame":
print("welcome")
else:
print("wrong password")
Run it on your computer
Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.py
name = input()
password = input()
# 1. Empty name: print "missing name".
# 2. Otherwise, password "open sesame": print "welcome".
# 3. Otherwise: print "wrong password".
print("wrong password")
test_main.py
from learnrun import run_main
def sign_in(name, password):
return run_main(f"{name}\n{password}\n").strip()
def test_welcome():
"""The right password is welcomed"""
got = sign_in("ada", "open sesame")
assert got == "welcome", f"for ada / open sesame the program printed {got!r}, expected 'welcome'"
def test_wrong_password():
"""A wrong password is refused"""
got = sign_in("ada", "open")
assert got == "wrong password", f"for ada / open the program printed {got!r}, expected 'wrong password'"
def test_missing_name():
"""An empty name is reported first, even with the right password"""
got = sign_in("", "open sesame")
assert got == "missing name", f"for an empty name the program printed {got!r}, expected 'missing name'"
On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.
Run the program:
python main.pyRun the checks (needs learnrun.py in the same folder):
python learnrun.py testDownload learnrun.pyCommon mistakes
One = in a condition
age = 20
if age = 18:
print("just an adult")
What Python prints
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?Why, and the fix
A single = assigns a value; it is not a question. To compare, write two: if age == 18:. Python refuses to run the file at all, and its message already suggests the fix.
Comparing text from input() with a number
age = "20" # what input() gives you: a string
if age >= 18:
print("adult")
What Python prints
TypeError: '>=' not supported between instances of 'str' and 'int'Why, and the fix
input() always returns a string, even when the user types digits, and Python will not order a string against a number. Convert first: age = int(input()). The error appears only when the line runs, so test your program with real input.
Forgetting to indent the branch
temperature = 35
if temperature > 30:
print("hot")
What Python prints
IndentationError: expected an indented block after 'if' statement on line 2Why, and the fix
The body of an if is the indented block under it: indentation is how Python knows which lines belong to the branch. Indent it by four spaces. In the editor on this page, Tab inserts four spaces.
Python in the browser: Pyodide 314.0.7, MPL-2.0. Licence and source
Exit ticket
5 questions, no hints. Score 80% or more to complete the lesson.
Finish every activity above to unlock the exit ticket.