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

Crew Quest

Crew Quest: Supply Sort
// if, elif and else
⏱ about 15 min

Crew Quest: Supply Sort

Three empty boxes sit in the cargo bay, labeled empty, low and full. Raven hands Rocket a stack of supply cards with numbers on them.

"Sort them," she says. "But first, what do you notice? We need a rule, and we need to ask the questions in the right order."

Rocket grins. "If it is zero, it goes in empty. Elif it is under five, low. Else, full!" Nova does a happy spin. "You just spoke Python," she says.

  1. A comparison gives True or False. The signs are <, >, <=, >=, == and !=.
  2. if runs when its comparison is True. else runs when it is False.
  3. elif asks the next question. The first True branch wins.
  4. The champion pattern finds the biggest value in a list.
  5. Test edge cases, like a number right on the line.
β—‡ SUPPLY SORT
Write ten numbers from 0 to 12 on scraps of paper.
Set out three bowls or boxes: empty, low and full.
Use the rule: 0 is empty, under 5 is low, everything else is full.
Sort the cards one at a time. Say the if, elif or else out loud.
Make up a new rule and sort again.
cards = [0, 7, 3, 12, 5]
full = 0
for c in cards:
    if c == 0:
        print("empty")
    elif c < 5:
        print("low")
    else:
        full = full + 1
print("Full cards:", full)
What number shows after Full cards: on the screen?
WHY THIS EXERCISEThis checks elif, else and a counter all at once.
BONUS RECAP
  • Read the question.
  • Tap your answer.
What does print(4 < 4) show?
Two branches are True. Which one runs?
The rule is five or fewer. Which sign makes 5 count?

Brilliant sorting! Next week, you will zoom in on strings, letter by letter.

← Friday