The storeroom has four shelves of supplies. Rocket wants the program to check every shelf and say ok or low. "Fewer than three is low," Raven decides.
Rocket writes a loop with an if inside. It prints low for the small shelves, but nothing at all for the others. "Hmm. What do you notice?" Raven asks. "The full shelves get no message."
Nova blinks. "Would you like a hint? An if can have a partner that runs when the answer is False."
if runs its lines when the comparison is True.
else runs its lines when the comparison is False.
Each item takes exactly one path. Inside a loop, Python decides again for every item.
shelves = [8, 2, 5, 1]
for s in shelves:
if s < 3:
print(s, "low")
else:
print(s, "ok") | The screen shows |
|---|
| 8 ok |
| 2 low |
| 5 ok |
| 1 low |
| Round | s | s < 3? | Path |
|---|---|---|---|
| 1 | 8 | False | else |
| 2 | 2 | True | if |
| 3 | 5 | False | else |
| 4 | 1 | True | if |
tanks = [12, 4, 9, 2, 7]
for t in tanks:
if t >= 5:
print("ok")
else:
print("refill") | Statement | True or false? |
|---|---|
| else runs when the if comparison is False. | ? |
| else has its own comparison, like else s > 3: | ? |
| The else line ends with a colon. | ? |
| An item can take the if path and the else path. | ? |
temps = [15, 22, 30, 18]
for t in temps:
if t > 20:
print(t, "warm")
else:
print(t, "cool") | Statement | True or false? |
|---|---|
| if runs its lines when its comparison is True. | ? |
| else runs every round. | ? |
| The comparison is checked again for each item. | ? |
| else must come before if. | ? |
Great choices! Tomorrow you will add a third path with elif.