else and elif
🌍 In real life. A teacher turns marks into a grade: 80 or more is A+, 70 or more is A, 60 or more is A-, and anything else gets a lower grade. The teacher checks from the top and stops at the first grade that fits: a mark of 85 is A+, even though 85 is also "70 or more".
elif and else let a program make that kind of choice between several options.
The idea in one sentence: Python checks the if, then each elif, from top to bottom, runs only the first block whose condition is True, and else catches everything left over.
Its words:
else: a block for when nothing above was True; it has no conditionelif: short for "else if": another condition, checked only if everything above was False- chain: an
ifwith itselifs andelse; exactly one block (or none, withoutelse) runs
Step by step, for age 15:
age >= 18? False, so skip that block.age >= 13? True, so runprint("teen").- Skip everything else in the chain, even the
else, and carry on below.
age = 15
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
else:
print("child")Why it works this way. Once one block has run, Python doesn't even look at the conditions below it. So the conditions can rely on the ones above being False: by the time Python asks age >= 13, it already knows the age is under 18.
That's also why order matters: put the strictest condition first. With the checks the other way round, a 20-year-old is called a teen:
age = 20
if age >= 13:
print("teen")
elif age >= 18:
print("adult")A plain if with an else is perfect for yes/no choices, like even or odd:
n = int(input("Number: "))
if n % 2 == 0:
print("even")
else:
print("odd")Mistakes and edge cases.
- A condition on else.
else n < 0:givesSyntaxError: expected ':'.elsenever has a condition; useelif. - elif without an if. An
elifat the start of a chain givesSyntaxError: invalid syntax. - Separate ifs instead of elif. Each
ifstarts a new chain, so more than one block can run. See below: 85 prints both A+ and A. - The wrong order. The loosest condition first catches everything; put the strictest first.
score = 85
if score >= 80:
print("A+")
if score >= 70:
print("A")Quiz
What does this print?
x = 0 if x > 0: print("positive") elif x < 0: print("negative") else: print("zero")What does this print?
score = 85 if score >= 50: print("pass") elif score >= 80: print("great")How many blocks of an if/elif/else chain run?
- Exactly one (or none, if there is no else)
- Every block whose condition is True
- Always all of them
Which line has a mistake?
x = 3 if x > 5: print("big") else x <= 5: print("small")What does this print?
t = 25 if t > 30: print("hot") elif t > 20: print("warm") else: print("cold")
Coding tasks
Ask for a whole number. Print
evenorodd.Ask for a test score from 0 to 100 and print the grade:
Afor 80 or moreBfor 60 to 79Cfor 40 to 59Fbelow 40
Ask for a temperature (a whole number). Print
hotif it is above 30,coldif it is below 10, andniceotherwise.