Lesson 6 · 6 of 20
Deciding with if, elif and else · Python
Make your Python program take decisions with if, elif and else: what to wear for the weather and whether delivery is free.

if checks a condition and, when it is true, runs the block underneath. The block is marked by indentation: the lines indented four spaces after the colon : are the ones that belong to the if.
elif (short for «else if») adds another condition that is only checked when the ones above have failed, and else catches everything else. Python goes from top to bottom and runs only the first one that is true: with temperature = 12, >= 25 fails, >= 15 fails and >= 5 matches, so it prints «take a coat».
elif and else are optional. if raining: stands on its own: since raining is True it prints the umbrella line; if it were False, nothing would happen.
With if and else you choose between two paths: the basket comes to 42.80 euros, which is under 50, so the program works out how much more is needed for free delivery. The last line is not indented, so it always runs.
Code · main.py
# The program decides what to wear from the temperature.temperature = 12if temperature >= 25: print("It is hot: wear a T-shirt.")elif temperature >= 15: print("It is mild: a light jacket will do.")elif temperature >= 5: print("It is cool: take a coat.")else: print("It is freezing: coat, scarf and gloves!")# Without elif or else: the block runs only if it is true.raining = Trueif raining: print("And take an umbrella.")# if ... else chooses between exactly two paths.basket = 42.80if basket >= 50: print("Free delivery!")else: print(f"Add {50 - basket:.2f} euros more for free delivery.")print("Have a nice day.") # not indented: it always runsOutput · python3 main.py
It is cool: take a coat. And take an umbrella. Add 7.20 euros more for free delivery. Have a nice day.
Key points
- After the condition comes a colon
:and an indented block. - In an
if/elif/elsechain only one block runs. - Order matters: put the strictest conditions first.
- A
boolvariable already works as a condition:if raining:.
Exercise
Try temperature = 30 and -2, and add a new elif for when it is over 35 degrees («Stay in the shade!»).