The Accumulator Pattern

Here is the single most useful loop pattern in programming, and you already know both halves of it:

1. Create a variable before the loop to hold the result

2. Update it inside the loop with +=

3. Use it after the loop

Counting, summing, filtering, finding a maximum. They're all this pattern with a different body.

EXAMPLE
loading editor…
YOUR TURN
Your turn → total goes 0 → 1 → 3 → 6 → 10, one addition per pass. Add a second accumulator, count, that goes up by one each pass, and print the average (total divided by count) after the loop.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Where total lives matters

total = 0 sits OUTSIDE the loop. Move it inside and it resets to zero on every pass, leaving you with only the last number. Initialize before, accumulate inside, use after, that order is the pattern.

Swap the body and the same skeleton filters, collecting only the items that pass a test.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Everything converges: collections, comparison, loops, and a condition. Change the cutoff year to 1980 and run it. Then build a second list that collects the titles published before 1800.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: break, continue, and Nested Loops →
← Back