The fuel gauge in Mission Control has four colors, not two. Green means ready, yellow means top up soon, orange means refuel before launch, and red means stop everything.
"My program only knows yes and no," Rocket says. "I need four answers."
Raven draws the gauge as a ladder with four steps. "What do you notice?" she asks. "We check from the top step down. The first step that fits is the answer."
Nova lights up each step in turn, top to bottom. "Interesting," she says. "Python has a word for else if. It checks the next condition only when the ones above it were False."
Rocket adds the middle steps to his program, carefully, from the top down.
elif is short for else if. Python checks the conditions from top to bottom and runs the block of the first one that is True. It skips all the rest, even if they are True too.
The else at the end catches everything that did not match. You can have as many elif parts as you need.
# fuel_gauge.py
fuel = int(input("Fuel percent: "))
if fuel >= 80:
print("Green: ready")
elif fuel >= 50:
print("Yellow: top up soon")
elif fuel >= 20:
print("Orange: refuel before launch")
else:
print("Red: do not launch") Fuel percent: 65 Yellow: top up soon
Here the steps are in the wrong order. The first condition catches almost everything, so the program gives the wrong color.
# gauge_bug.py (conditions in the wrong order)
fuel = 90
if fuel >= 20:
print("Orange")
elif fuel >= 80:
print("Green") Here is another ladder of conditions. This time the thresholds go up, so the program checks the smallest one first with less than.
# wind_level.py
wind = int(input("Wind speed in km per hour: "))
if wind < 20:
print("Calm")
elif wind < 40:
print("Breezy")
elif wind < 60:
print("Windy")
else:
print("Too windy to launch") Wind speed in km per hour: 40 Windy
| Statement | True or false? |
|---|---|
| A chain of if, elif and else runs at most one block. | ? |
| You can have only one elif in a chain. | ? |
| If no condition is True and there is no else, nothing in the chain runs. | ? |
| Python checks every elif even after one is True. | ? |
Testing the values right on each line, like 80, 50 and 20, is how programmers catch mistakes. Tomorrow you will combine conditions with and, or and not.