Build a Running Summary
Carry a total and count across the readings, trace every update, and calculate the hand-checked mean. Read += only after the explicit reassignment is clear.
Printing each reading does not answer the original question. To find a mean, the loop must carry a total and count across its iterations.
Start with Known State
Initialize both summary values before the loop:
The values a program currently remembers are its state. Here, that state is
the current total and count. The right side of each update uses the previous
value. The assignment then makes the name refer to the new result.
| Reading | total after update | count after update |
|---|---|---|
| start | 0 | 0 |
| 18 | 18 | 1 |
| 21 | 39 | 2 |
| 20 | 59 | 3 |
| 23 | 82 | 4 |
After the loop, the mean is total / count, or 20.5.
Trace a running summary
Predict every total and count, then run the complete summary and compare the final report.
Ready to run.
Updating Is Different from Replacing
This incorrect body forgets earlier work:
After the loop, total is only the last reading, 23. A running summary must
combine the previous total with the current reading.
Initialization belongs before the loop. If total = 0 is indented inside the
body, every iteration erases the earlier sum before adding the current value.
Q1. Find the lost total
What is total after this loop?
Compute it first, then check your number.
HintFollow replacement, not addition
The body assigns 3, then 5, then 4 to the same name.
SolutionOnly the last reading remains
The final assignment is total = 4, so the final value is 4 rather than 12.
Read the Short Update Form
After the explicit update is clear, Python offers a shorter equivalent:
For these numerical names, total += reading performs the same update as
total = total + reading. The shorter form does not remove the need for an
initial value or change the order of the loop.
Q2. Complete total and count
Complete the loop so the program displays total: 12 and count: 3.
Editable Python
Ready to run.
HintUpdate both names inside the body
Use total += reading and count += 1 at the same indentation.
SolutionCarry both values across iterations
Q3. Place initialization correctly
Where should total = 0 appear when the goal is one sum over the complete
list?
Select one choice, then check.
HintInitialize once
The summary needs one starting state for the entire loop.
SolutionInitialize before repetition
A single total = 0 before the loop establishes the starting state. The
body then updates that same running total.
A running summary begins with explicit state and updates it once per value. Tracing every intermediate total and count makes the final mean checkable. Next we consider repetition whose end is controlled by a changing condition.