Running Totals
A running total is a value that accumulates as a loop runs.
Output:
12
This pattern appears everywhere: sum losses, count tokens, accumulate correct predictions, compute averages, and build simple statistics.
Start with an Initial Value
The total must exist before the loop:
total = 0
Then each iteration updates it:
total = total + value
Read that line carefully:
- compute the right side using the current total
- assign the new value back to
total
Trace the Loop
For [3, 4, 5]:
| Iteration | value | old total | new total |
|---|---|---|---|
| 1 | 3 | 0 | 3 |
| 2 | 4 | 3 | 7 |
| 3 | 5 | 7 | 12 |
Show the running total
Printing inside the loop makes the accumulation visible.
Ready to run.
Averages
An average is a total divided by a count:
len(values) returns the number of items in the list. Here that count is 3.
Output:
4.0
We will later write this as a function. For now, the loop pattern matters.
Initialize the Total Before the Loop
Do not reset the total inside the loop:
That restarts the total every iteration. Initialize before the loop.
What final total does this program print?
Compute it first, then check your number.
HintCarry the total forward
Begin at zero, then add 2, then 5, then 1 without resetting.
SolutionThe final total is eight
The running totals are 2, 7, and 8. After the final iteration,
print(total) prints 8.
Accumulators Remember Work Across Iterations
Running totals make repeated computation visible. If a loop feels abstract, print the total after each update.