Totals and counters
You often need to add up the numbers in a list, or count how many items meet some test. Both use the same trick: a variable that starts at zero and grows as the loop runs. This is the accumulator pattern.
Summing with a running total
Start a total at 0, then add each item to it inside the loop:
Walk through it:
- Before the loop,
totalis0 - Pass 1:
total = 0 + 88->88 - Pass 2:
total = 88 + 92->180 - Pass 3:
total = 180 + 75->255
The variable accumulates the result one item at a time. Starting at 0 matters — it's the correct starting point for addition.
A shortcut: +=
total = total + score is so common that Python gives you a shorthand, +=:
Both do exactly the same thing. Use whichever is clearer to you.
Counting with a counter
To count how many items pass a test, start a counter at 0 and add 1 each time the test is true:
Only 88, 92, and 75 are 70 or above, so the counter ends at 3.
Averaging combines both ideas
An average is just a total divided by a count:
Key takeaways
- The accumulator pattern uses a variable that starts at
0and grows inside a loop - Sum: add each item —
total += item - Count: add
1when a condition is true —count += 1 +=is shorthand for "add to the existing value"- Average = total ÷
len(list)
No comments yet. Add the first comment to start the discussion.