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

Wednesday

A running total
// Visit every item
⏱ about 15 min

Wednesday: A running total

Rocket is planning the fuel budget for three shuttle trips. The trips need 12, 8 and 15 units of fuel. "How much fuel do we need in all?" he asks.

He tries adding in his head, but he keeps losing the number. Raven grabs a notepad. "What do you notice when I add? I keep one number and grow it after each trip."

Nova projects a small glowing counter that starts at zero. "Would you like a hint? A loop can carry a total, just like Raven's notepad."

Start at 0, then keep adding

A running total starts at 0 before the loop.

Inside the loop, each value is added to the total.

After the loop, the total holds the sum of every value.

trips = [12, 8, 15]
total = 0
for f in trips:
    total = total + f
print("Total fuel:", total)
The screen shows
Total fuel: 35
Roundftotal after the round
before the loopnone yet0
11212
2820
31535
trips = [5, 10, 20]
total = 0
for f in trips:
    total = total + f
print(total)
total after round 1
total after round 2
total after round 3
trips = [6, 9, 4, 11]
total = 0
for f in trips:
    total = total + f
print("Total fuel:", total)
What number shows after Total fuel: in the program above?
WHY THIS EXERCISEThe same loop works for any list. Only the numbers change.
WHY START AT 0?
  • Read the question.
  • Tap your answer.
Why does total start at 0?
Try it
Ask a grown-up to say four small numbers.
Keep a running total on paper after each one.

Practice lab: total the water

water = [4, 10, 6, 5]
total = 0
for w in water:
    total = total + w
print("Water used:", total)
total after round 1
total after round 2
total after round 3
total after round 4
TOTAL CHECK
  • Read the question.
  • Tap your answer.
trips = [2, 2, 2]. What total does the loop give?
Where does total = 0 go?
Where does the print go to show the total one time?
StatementTrue or false?
A running total starts at 0.?
total = total + w adds w to the total.?
The total is printed before the loop.?
The same loop works for any list of numbers.?
WHY THIS EXERCISEStart, loop, then show. That pattern adds up any list.
Use the loop to total this list: [7, 3, 10]. What is the total?
WHY THIS EXERCISEThe loop adds every value once, so the total is the sum of the list.

You built a running total! Programmers use this pattern everywhere. Tomorrow you will count only the items that match.

← Tuesday