Course outline · 0% complete

0/27 lessons0%

Course overview →

Accumulating: totals and counts

lesson 5-3 · ~11 min · 17/27

The accumulator pattern

Here is the pattern that unlocks most beginner programs. To add up the numbers 1 through 5:

total = 0
for n in range(1, 6):
    total = total + n
print(total)

Three parts, all of them ideas you already own:

  1. Start an accumulator variable before the loop: total = 0 (lesson 3-1)
  2. Update it inside the loop body each iteration: total = total + n (lesson 3-2)
  3. Use it after the loop: print(total)

Trace it: total goes 0 → 1 → 3 → 6 → 10 → 15. The final print shows 15.

The same shape counts things. To count how many numbers from 1 to 20 are even, start count = 0 and add 1 only when a condition holds, using if inside the loop (lesson 4-2) and the remainder operator % from lesson 2-2: a number is even when n % 2 == 0.

Code exercise · python

Two accumulators: a sum and a conditional count. Run it and check both results by hand.

Quiz

In the accumulator pattern, why must total = 0 come BEFORE the loop instead of inside it?

Code exercise · python

Your turn. Use the accumulator pattern to compute the sum of all numbers from 1 to 100 (a famous result). Print only the final total.