The fleet radio picks up signals from four stars. Some are loud, and some are barely a whisper.
Rocket wants each signal labeled strong, medium or faint. "I will read every number and decide," he says. He yawns at the third one.
Raven looks over the list. "What do you notice about the rule you use?"
"Big numbers are strong. Middle ones are medium. Small ones are faint," Rocket says.
Nova flashes. "Here is a hint. A rule with three choices fits if, elif and else."
Python checks the if first. If it is false, it checks the elif. If that is false too, the else runs.
Only one of the three choices runs for each item.
signals = [8, 3, 5, 1]
for s in signals:
if s >= 7:
print("strong")
elif s >= 4:
print("medium")
else:
print("faint") Output: strong faint medium faint
| Symbol | Meaning | Example that is True |
|---|---|---|
| == | is equal to | 5 == 5 |
| != | is not equal to | 3 != 4 |
| < | is less than | 2 < 9 |
| > | is greater than | 9 > 2 |
| <= | is less than or equal to | 4 <= 4 |
| >= | is greater than or equal to | 7 >= 7 |
| Comparison | True or false? |
|---|---|
| 5 >= 5 | ? |
| 3 != 3 | ? |
| 2 < 9 | ? |
| "Glow" == "glow" | ? |
temps = [35, 18, 2, 25]
for t in temps:
if t >= 30:
print(t, "hot")
elif t >= 15:
print(t, "warm")
elif t >= 5:
print(t, "cool")
else:
print(t, "cold") | Comparison | True or false? |
|---|---|
| 5 >= 5 | ? |
| "Hot" == "hot" | ? |
| 14 >= 15 | ? |
| 3 != 4 | ? |
Well done! You read a three-way choice like a pro. Tomorrow we return to dictionaries, the catalog of keys and values.