Learn Python · lesson 14 of 60 · about 8 minutes
elif and Nested Conditions
Tell Sam what to wear from the temperature: choose between many options with elif, and put decisions inside decisions.
What you'll learn
- Chain options with elif
- Know that only the first True branch runs
- Nest an if inside another
What to wear
Sam wants the assistant to say what to wear: a coat when it's cold, a jumper when it's mild and a T-shirt when it's warm. That's three choices, and if with else only gives you two.
More than two options
elif (short for "else if") adds more conditions. Python checks them from top to bottom and runs only the first one that is True. else at the end catches everything left over.
Medals
place = 2
if place == 1:
print("Gold")
elif place == 2:
print("Silver")
elif place == 3:
print("Bronze")
else:
print("Well done for taking part")Output
SilverOrder matters: the first True wins
score = 95
if score >= 50:
print("Pass")
elif score >= 90:
print("Top marks")Output
PassColdest first
Check in one direction. temp < 10 has to come before temp < 20: the other way round, 5 degrees would match temp < 20 first and get a jumper. And because the temperature is typed, it arrives as text, so turn it into a number with int() before comparing.
What to wear
temp = int(input("Temperature? "))
if temp < 10:
print("Wear a coat")
elif temp < 20:
print("A jumper is enough")
else:
print("T-shirt weather!")Output
Temperature? A jumper is enoughDecisions inside decisions
An if can sit inside another if's block. The inner one is only checked when the outer one is True. Indent it one more level.
Nested if
logged_in = True
is_premium = False
if logged_in:
if is_premium:
print("Unlimited fuel")
else:
print("Fuel: 5")
else:
print("Please sign in")Output
Fuel: 5Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.