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

Thursday

Find what you need
// if, elif and else
⏱ about 15 min

Thursday: Find what you need

A long trip is coming, and Rocket needs the biggest fuel tank on the station. There are four tanks. "Let's just look at them all," he says, and he starts reading numbers out loud.

Raven grabs a sticky note. "What do you notice? I only write down a number when I find a bigger one."

Nova draws a glowing crown above the first tank. "Interesting! Would you like a hint? Keep a champion. Swap it whenever a bigger value comes along."

Find the biggest

Start with the first item as the champion. Then loop through the list.

If an item is bigger than the champion, it becomes the new champion.

tanks = [40, 75, 30, 60]
biggest = tanks[0]
for t in tanks:
    if t > biggest:
        biggest = t
print("Biggest tank:", biggest)
The screen shows
Biggest tank: 75
Roundtt > biggest?biggest after the round
before the loopnone yetnone yet40
140False40
275True75
330False75
460False75
tanks = [25, 18, 52, 47]
biggest = tanks[0]
for t in tanks:
    if t > biggest:
        biggest = t
print(biggest)
biggest after round 2
What does the program show?

Collect the low ones

A loop can also build a new list. Start empty, then append each item that matches.

tanks = [40, 15, 30, 10]
low = []
for t in tanks:
    if t < 20:
        low.append(t)
print(low)
print(len(low))
The screen shows
[15, 10]
2
Change the if line to if t < 35:. How many tanks are in the low list now?
WHY THIS EXERCISEChanging one comparison changes what the whole loop collects.
Try it
Ask a grown-up to say five numbers.
Keep a champion on paper and swap it when a bigger one comes.
temps = [14, 9, 21, 6, 12]
smallest = temps[0]
for t in temps:
    if t < smallest:
        smallest = t
print("Coldest:", smallest)
smallest before the loop
smallest after round 2
smallest after round 3
What number shows after Coldest:?
CHAMPIONS AND COLLECTORS
  • Read the question.
  • Tap your answer.
To find the smallest value, which sign goes in the if?
Why start with temps[0] as the champion?
A loop appends each item over 10 from [5, 12, 30, 8]. What is the new list?
StatementTrue or false?
The champion only changes when a better value comes.?
The champion changes every round.?
A loop can build a new list with append.?
The low list starts with one item in it.?
WHY THIS EXERCISEChampions change only on a win. Collector lists start empty.
Use the champion pattern on [3, 17, 9, 17, 4]. What is the biggest value?
WHY THIS EXERCISE17 wins in round 2. The second 17 is not bigger, so nothing changes.

You found the champion and collected the low tanks! Tomorrow you will debug choices that went wrong.

← Wednesday