← Back to course
Code Crew G4 / Week 03 / Friday
5/6
Week 03 Β· Loop through a list

Friday

Debug the loop
// Visit every item
⏱ about 15 min

Friday: Debug the loop

The fuel budget program is ready for the big meeting. Rocket runs it, and it says the trips need only 15 units of fuel. "That is way too low," he says. "We can improve it."

Raven makes a trace table on her notepad. "What do you notice about total each round?" she asks. "It keeps going back to zero," Rocket says.

Nova highlights one line in red. "Let's debug together. Would you like a hint? Look at where total gets its starting value."

Bug 1: the total keeps resetting

This program should show 35. It shows 15. Read it carefully.

trips = [12, 8, 15]
for f in trips:
    total = 0
    total = total + f
print("Total fuel:", total)
Roundftotal after the round
11212
288
31515
FIX BUG 1
  • Read the question.
  • Tap your answer.
How can Rocket fix the program?

Bug 2: too many lines

Rocket wants just one line on the screen. Read this version.

trips = [12, 8, 15]
total = 0
for f in trips:
    total = total + f
    print("Total fuel:", total)
How many lines show on the screen?
What number is on the last line?
Change to bug 2Does it make just one line show?
Take the indent off the print line?
Indent the total = 0 line?
Delete the print line?
WHY THIS EXERCISEDeleting the print shows nothing at all. Moving it out of the loop shows the total once.
At the computer
This is never required.
If you have Python from python.org, type bug 2 into IDLE.
Run it, then fix the indent and run it again.

Bug 3: counting too much

This program should count the full tanks. Only two tanks are full, but the last line shows 3.

tanks = ["full", "empty", "full"]
count = 0
for t in tanks:
    if t == "full":
        print("Full tank")
    count = count + 1
print(count)
FIX BUG 3
  • Read the question.
  • Tap your answer.
What is the bug?
How many times does Full tank show?
After the fix, what does the last line show?
Change to the fixed programDoes the last line still show 2?
Move count = 0 inside the loop, above the if?
Change the list to ["empty", "full", "full"]?
Count "empty" instead of "full"?
Add one more "full" to the end of the list?
WHY THIS EXERCISESmall moves change a program a lot. Tracing each change is how engineers test a fix.
Try it
Write the three tank words on scraps of paper.
Walk the loop with your finger, one scrap at a time.
Make a tally mark only when the tank is full.
Look back at bug 1. How many times did total = 0 run?
WHY THIS EXERCISEInside the loop, the reset ran every round. That is why the total was wrong.

Week three is done, Crew Engineer! You can loop, total and count. Next week, loops will make choices with if, elif and else.

← Thursday