Knowledge Institute · 8–10 minutes with practice

Carry counts and totals through a Python loop

Trace a loop by stating what each variable means after every row, including rows the rule excludes.

Foundations & Science Quick Courses

Learning objectives

Learn

For a mean, the loop can store the total of accepted values and the count of those values. Before the first record both totals are zero. After each advance, both must describe the same accepted portion of the input. A rejected record leaves both unchanged. At the end divide only if the count is positive and use the contract’s defined output for the empty case. Correct arithmetic depends on the inclusion rule as much as on the division.

Correctness and termination are separate obligations

A prefix invariant alone does not prove that a loop ever finishes. In the indexed while implementation, let index identify the next element. At each successfully reached loop head, the state summarizes rows[:index]. The nonnegative integer len(rows)-index is a termination measure for a fixed finite sequence. Each iteration increments index exactly once, including a missing-value iteration. Thus the measure strictly decreases until the exit condition is reached. The loop proof assumes that the sequence length is not being changed concurrently.

If an implementation handles None with continue before advancing index, it repeatedly visits that same missing record. Its accumulator might remain internally consistent while execution never reaches the next element. Fix the progress step, rather than silently deleting missing records from the specification. A for loop over an iterator advances through its iteration mechanism, but an infinite or blocking input source does not acquire a termination guarantee merely because the syntax says for.

Combine sufficient statistics, not averages

Suppose two disjoint input chunks have valid six-field summaries. Add corresponding fields to obtain the summary of their concatenation. Counts and integer sums are additive, so the prefix definitions prove this component-wise merge. The empty summary is an identity, and regrouping merges changes no integer sum. These facts support chunked processing for the specified report. They do not establish exactly-once delivery: merging the same chunk twice counts it twice, and overlapping chunks double-count their overlap.

A chunk's mean alone loses its denominator. Chunk A contains [100], and chunk B contains [0,0,0]. Their sales means are 100 and 0, but the combined mean is (100+0)/(1+3)=25, not (100+0)/2=50. In general, retain each sum S and count n, then compute (S1+S2)/(n1+n2) when the combined count is positive. This also handles an empty chunk without inventing an average for it. The same rule applies to present-record means with their own counts.

The six fields are sufficient for these totals and means. They cannot reconstruct record order, a median or the first record crossing a cumulative threshold. Although the completed summary is unchanged by permuting valid amounts, the prefix states and the first failure encountered can change. Do not transfer a commutative arithmetic argument to a workflow that sends messages or records external effects on each iteration.

Prove what each branch preserves

A state should retain exactly the information the requested report needs. For this record stream, use six fields: processed, missing, sales_count, sales_cents, refund_count and refund_cents. Every input is either None for missing or an integer number of cents; booleans, text and floating-point values are rejected. Zero is a present sale observation. A negative amount is a refund. These are reporting rules for this exercise, rather than a universal rule about all financial records.

First trace the six fields as ordinary accumulator variables. The executable companion packages those same fields in a Summary record. Its frozen dataclass declaration creates a small named record whose field values cannot be reassigned through the ordinary interface; step returns a new record rather than changing the old one. The loop, branches and arithmetic remain inspectable separately from that convenience syntax. Begin with the hand trace before studying the implementation.

Apply

Suppose one file has the three readings 10, missing, and 20. The accepted count moves from zero to one, stays one, and then becomes two. Its total is 30 and mean is 15. A second file contains the single valid reading 30, with a mean of 30. Combining all valid observations gives a total of 60 with count three and mean 20. Simply averaging the two file means would yield 22.5 because that assigns both files the same weight. A program that emits both the count and total makes the pooled result traceable. Include a test with only missing values and specify whether missing values can be excluded or should trigger a separate report.

Optional check

If one group has zero valid readings, should the pooled calculation substitute a group mean of zero?

Show the explained answer

Its total and count contribute zero to a pooled mean of valid observations. A numeric mean for the empty group would misrepresent its data. Record that the group contains no accepted readings, and return the specified empty-case result if the pooled count is zero.

Sources and further reading

Continue in Lawfare Academy

Full course · CS 101 — Programming Foundations with Python