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

Friday

Debug the choices
// if, elif and else
⏱ about 15 min

Friday: Debug the choices

The crew has a new rule: five units or fewer means a shelf is low. Rocket runs his supply check. The shelf with exactly five units says ok.

"That shelf should be low," Raven says. "What do you notice about the comparison sign?"

Rocket looks at it for a long time. "It says less than. But five is not less than five." Nova glows softly. "Great discovery! Would you like a hint? One more symbol can make the tie count."

Bug 1: the edge case

A number right on the line, like 5 in this rule, is called an edge case.

Edge cases are where many bugs hide. Always test them.

shelves = [6, 5, 2]
for s in shelves:
    if s < 5:
        print(s, "low")
    else:
        print(s, "ok")
The screen shows
6 ok
5 ok
2 low
FIX BUG 1
  • Read the question.
  • Tap your answer.
The rule is five or fewer is low. Which if line fixes the program?

Bug 2: = or ==?

Rocket typed if s = 5: by mistake. Python stops before running anything and shows a SyntaxError.

A single = stores a value. Inside an if, you need == to ask a question.

LineWill Python accept it?
if s == 5:?
if s = 5:?
if s <= 5:?
if s < 5?
WHY THIS EXERCISEMost choice bugs are one wrong sign or one missing colon.
temps = [18, 25, 21]
for t in temps:
    if t > 22:
        print("warm")
    elif t > 20:
        print("just right")
    else:
        print("cool")
PUT THE SCREEN LINES IN ORDER FOR THE PROGRAM ABOVE
  • ?cool
  • ?warm
  • ?just right
WHY THIS EXERCISETracing in order is how you test a program before anyone runs it.
At the computer
This is never required.
If a grown-up has set up Python from python.org, type bug 1 into IDLE.
Run it, fix the sign, then run it again.

Bug 3: the branch that never runs

The rule is over 90 is great and over 60 is good. Every score below says good.

scores = [95, 70, 85]
for s in scores:
    if s > 60:
        print(s, "good")
    elif s > 90:
        print(s, "great")
    else:
        print(s, "keep going")
FIX BUG 3
  • Read the question.
  • Tap your answer.
Which branch can never run?
How can Rocket fix it?
After the fix, what does round 1 show?
Score in the fixed programDoes it show good?
70?
95?
61?
60?
WHY THIS EXERCISE60 is an edge case. 60 > 60 is False, so it shows keep going.
In the buggy program, how many lines say good?
WHY THIS EXERCISEThe good branch caught every score, so the bug hid the great label.
Try it
Write the scores 95, 70 and 85 on scraps of paper.
Sort them with the fixed rule: great, good or keep going.
Say each question out loud, in order, for every scrap.

Week four is done! Your loops can choose. Next week, you will look closely at strings.

← Thursday