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."
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 |
| Round | f | total after the round |
|---|---|---|
| before the loop | none yet | 0 |
| 1 | 12 | 12 |
| 2 | 8 | 20 |
| 3 | 15 | 35 |
trips = [5, 10, 20]
total = 0
for f in trips:
total = total + f
print(total) trips = [6, 9, 4, 11]
total = 0
for f in trips:
total = total + f
print("Total fuel:", total) water = [4, 10, 6, 5]
total = 0
for w in water:
total = total + w
print("Water used:", total) | Statement | True 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. | ? |
You built a running total! Programmers use this pattern everywhere. Tomorrow you will count only the items that match.