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

Wednesday

Three paths with elif
// if, elif and else
⏱ about 15 min

Wednesday: Three paths with elif

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: the next question

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.

WHICH LABEL?
  • Read the question.
  • Tap your answer.
In the program above, suppose the list holds 5. What does that round show?
Suppose the list holds 3. What does that round show?

Order matters

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")
What does the first line on the screen say now?
WHY THIS EXERCISEThe first True branch wins. Put the most exact check first, or it never gets a turn.
Statement about Rocket's swapped versionTrue or false?
The empty branch can never run.?
9 still shows full.?
4 shows empty.?
WHY THIS EXERCISEA branch that can never run is a hidden bug. Careful order finds it.
Try it
Make a three-path rule for the weather: hot, mild or cold.
Decide which question to ask first.

Practice lab: three speeds

speeds = [2, 6, 11, 8]
for s in speeds:
    if s > 10:
        print("fast")
    elif s > 5:
        print("cruise")
    else:
        print("slow")
What does round 1 show?
What does round 3 show?
How many times does cruise show?
ELIF CHECK
  • Read the question.
  • Tap your answer.
What does elif mean?
How many branches run for one item?
Suppose the list held 10. What would that round show?
StatementTrue 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.?
WHY THIS EXERCISEif, elif and else make one choice from many. Only one branch runs.
In the speeds program, which word shows for a speed of 5?
WHY THIS EXERCISE5 is right on the edge. Both questions are False, so else runs.

You tamed three paths! Tomorrow loops with choices will find the supplies we need.

← Tuesday