What is for lunch?
If there is pizza, I pick pizza. Else if there is pasta, I pick pasta. Else, a sandwich.
04CONDITIONALS · ELIF
elif is short for “else, if”. It asks a new question only when every question above it was False.
IN REAL LIFE
You ask your favorite first. If it is not there, you ask for the next one.
If there is pizza, I pick pizza. Else if there is pasta, I pick pasta. Else, a sandwich.
If 6 friends come, we play soccer. Else if 2 come, we play tag. Else, I build with blocks.
If they have chocolate, I take it. Else if they have strawberry, I take that. Else, vanilla.
LOOK FIRST
The first question always goes with if.
If the answer above was False, elif asks another question. You can add as many as you need.
If every answer was False, the else path runs. It is optional.
STEP BY STEP
PyBot reads one question at a time, from the top.
light = "yellow"A box keeps the word yellow.if light == "green":Is it green? No. Go down to the next question. print("go")Skipped.elif light == "yellow":Is it yellow? Yes! print("slow down")This path runs.elif light == "red":Not even asked. A path already ran. print("stop")Skipped.else:Skipped. else only runs when every answer was False.LOOK FIRST
Python stops at the first True. The questions below it are not asked.
Put the hardest question first. score >= 9 goes before score >= 5.
With two separate ifs, both can run. With elif, only one path runs.
RUN IT
Guess first. Then run real Python and check.
score = 7
if score >= 9:
print("gold")
elif score >= 5:
print("silver")
else:
print("bronze")What will Python show?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Change 7 to 10, then to 2. Which medal does PyBot get each time?
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
What does PyBot eat?
What does elif mean?
light = "red"
if light == "green":
print("go")
elif light == "yellow":
print("slow down")
elif light == "red":
print("stop")What does Python show?
n = 15
if n > 5:
print("big")
elif n > 10:
print("huge")What does Python show?
What should PyBot change?
pet = "fish"
if pet == "dog":
print("woof")
elif pet == "cat":
print("meow")What does Python show?
battery = 90
if battery > 50:
print("play")
if battery > 80:
print("dance")Which words show?
How many elif lines can one if have?
Python does not know else if on one line. Use its short word.
stopOUTPUT
Want a fresh start? Clear only this page.
Next: when you compare one box with many values, Python has match.