The fuel gauges need three labels now: empty, low and full. Rocket writes two if lines in his loop. When a tank is empty, the screen says empty and also low!
"Two messages for one tank?" Raven asks. "What do you notice? Zero is less than five too, so both checks were True."
Nova lights up three little lamps, one after another. "Would you like a hint? Python has a word for asking the next question only if the first answer was False."
elif is short for else if. It asks another question, but only when the questions above it were False.
Python checks from the top down. The first True branch runs. Every branch below it is skipped.
levels = [0, 4, 9]
for n in levels:
if n == 0:
print(n, "empty")
elif n < 5:
print(n, "low")
else:
print(n, "full") | The screen shows |
|---|
| 0 empty |
| 4 low |
| 9 full |
With 0, the first question is True, so Python prints empty and skips the rest. That fixes Rocket's double message.
Rocket swapped the first two questions. Read his version.
levels = [0, 4, 9]
for n in levels:
if n < 5:
print(n, "low")
elif n == 0:
print(n, "empty")
else:
print(n, "full") | Statement about Rocket's swapped version | True or false? |
|---|---|
| The empty branch can never run. | ? |
| 9 still shows full. | ? |
| 4 shows empty. | ? |
speeds = [2, 6, 11, 8]
for s in speeds:
if s > 10:
print("fast")
elif s > 5:
print("cruise")
else:
print("slow") | Statement | True or false? |
|---|---|
| Python checks the branches from the top down. | ? |
| Every True branch runs. | ? |
| else runs when every question above it is False. | ? |
| elif comes after an if. | ? |
You tamed three paths! Tomorrow loops with choices will find the supplies we need.