← Back to course
Code Crew G5 / Week 01 / Wednesday
3/6
Week 01 Β· Crew check

Wednesday

Choices inside a loop
// The tools you already have
⏱ about 15 min

Wednesday: Choices inside a loop

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."

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
SymbolMeaningExample that is True
==is equal to5 == 5
!=is not equal to3 != 4
<is less than2 < 9
>is greater than9 > 2
<=is less than or equal to4 <= 4
>=is greater than or equal to7 >= 7
USE THE SIGNAL PROGRAM. WHICH WORD PRINTS FOR EACH NUMBER?
  • Read the question.
  • Tap your answer.
What prints when s is 7?
What prints when s is 4?
What prints when s is 0?
ComparisonTrue or false?
5 >= 5?
3 != 3?
2 < 9?
"Glow" == "glow"?
WHY THIS EXERCISEPython compares exactly, so a capital G and a small g are different letters.
Run the signal program with signals = [2, 9, 4, 0, 6]. How many times does "medium" print?
WHY THIS EXERCISEThe elif only runs when the if before it was false, so 9 is strong, not medium.

Practice lab: four labels

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")
How many lines say warm?
What word follows 2?
What word would follow 5?
What word would follow 30?
BRANCH CHECK
  • Read the question.
  • Tap your answer.
How many branches can run for one number?
Suppose t >= 15 were checked first. What would 35 print?
Which comparison is True?
ComparisonTrue or false?
5 >= 5?
"Hot" == "hot"?
14 >= 15?
3 != 4?
WHY THIS EXERCISEEvery branch depends on comparisons like these.
How many numbers in [30, 29, 15, 14, 5, 4] print cool?
WHY THIS EXERCISE14 and 5 are cool. 4 is cold, and the rest are warm or hot.

Well done! You read a three-way choice like a pro. Tomorrow we return to dictionaries, the catalog of keys and values.

← Tuesday