if / elif / else, explained simply
A plain if handles one situation. Real decisions often have several: if it is cold wear a coat, if it is mild wear a jumper, otherwise wear a T-shirt.
elif is short for "else if". Python checks the if first, then each elif in order, and runs the first block whose question is True. It skips all the rest.
else comes last and has no question. It catches every case the earlier checks did not. That makes sure your program always has an answer.
Example: Dress for the weather
temperature = 18
if temperature < 10:
print("Wear a warm coat")
elif temperature < 22:
print("A jumper will do")
else:
print("T-shirt weather!")Output
A jumper will doTry this
- Try temperatures of 5, 21 and 30. Which block runs each time?
- Swap the order of the first two checks and find the temperature that now gives a silly answer.
- Add another elif for rainy days using a second variable.
