Choose your own adventure.
Use if, elif, and else to give your program more than one path.
01 The idea
An if statement selects a block when its condition is truthy. elif adds another condition, checked only if the earlier conditions failed. else is the fallback. In one if/elif/else chain, only the first matching branch runs.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
charge = 42
if charge >= 80:
status = "Ready for launch"
elif charge >= 30:
status = "Short mission only"
else:
status = "Recharge first"
print(status)Short mission only
03 Under the hood
- 1
42 is below 80, so Python skips the first block. It then checks the elif condition.
- 2
42 is at least 30, so status becomes "Short mission only". Python skips the remaining else block.
- 3
Order matters. Put the more specific or higher-threshold condition first when your conditions overlap. Separate if statements are appropriate when multiple independent actions should happen.
04 Your turn, builder
Classify a score: 80 or more is "gold", 50 or more is "silver", and everything else is "keep going". Test with 67.
Reveal one possible solution +
score = 67
if score >= 80:
print("gold")
elif score >= 50:
print("silver")
else:
print("keep going")05 Check your signal
How many branches run in one if/elif/else chain?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.