← Back to course
Code Crew G4 / Week 04 / Tuesday
2/6
Week 04 Β· Choices in a loop

Tuesday

if and else in a loop
// if, elif and else
⏱ about 15 min

Tuesday: if and else in a loop

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

Two paths: if and else

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
Roundss < 3?Path
18Falseelse
22Trueif
35Falseelse
41Trueif
tanks = [12, 4, 9, 2, 7]
for t in tanks:
    if t >= 5:
        print("ok")
    else:
        print("refill")
What does round 2 show?
How many times does refill show?
StatementTrue 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.?
WHY THIS EXERCISEelse needs no question. It catches every item the if did not.
Try it
Pick a rule, like five or more is a big number.
Your grown-up says numbers. You say big or small for each one.

Practice lab: warm or cool?

temps = [15, 22, 30, 18]
for t in temps:
    if t > 20:
        print(t, "warm")
    else:
        print(t, "cool")
What word does round 1 show?
How many times does warm show?
What word does round 4 show?
ONE PATH EACH
  • Read the question.
  • Tap your answer.
How many paths does each item take?
What comes after the word else?
Suppose the list held 20. What would that round show?
StatementTrue 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.?
WHY THIS EXERCISEif comes first and asks. else catches what is left.
nums = [3, 8, 1, 9, 6]. The loop has if n > 5 and an else. How many times does the if path run?
WHY THIS EXERCISE8, 9 and 6 pass the test. The other two take the else path.

Great choices! Tomorrow you will add a third path with elif.

← Monday