The Knowledge Institute
← Back to library

Programming Foundations · 2 MIN READ

Follow a loop without losing count

Trace the items actually visited and the value carried from one repetition to the next.

Repetition needs a clear unit

A loop applies instructions repeatedly. A Python for loop visits items from an iterable, such as a list. Describe what one iteration processes: one invoice, one measurement, or one character. A running total carries information between iterations. Initialize it before the loop, then update it for each relevant item. Resetting it inside the loop destroys the accumulated result.

Worked example: three invoices

Imagine invoices of 12, 7, and 11 dollars. Begin with total = 0. Adding 12 produces 12; adding 7 produces 19; adding 11 produces 30. If total = 0 is repeated before each addition inside the loop, the final value is 11 instead of 30. A second trace column for the iteration number makes this difference visible. An empty list leaves the correctly initialized total at zero because no addition runs.

Check what is visited

Python range(3) produces 0, 1, and 2: its stop value is excluded. Do not assume that a label such as “three items” implies indices 1 through 3. For a nonempty average, divide the total by the number of included measurements; decide how an empty collection should be reported before dividing. Missing measurements and genuine zero values require different treatment. A loop over the wrong records can yield exact arithmetic and a misleading conclusion.

Put it to work

Trace totals for [4, 0, 9] and for an empty list. Explain why an empty average needs a separate rule.

Knowledge check

1. Where should a running total normally start at zero?
2. Which values does Python range(3) produce?

Sources & further reading