Loop Invariants and Chunked Reports
Original teaching, synthetic records and a complete executable laboratory. Trace the branches, prove progress, change the reporting question and test what a failed iterator consumes.
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.
At a successful loop head after k inputs, processed=k; missing counts None in that prefix; sales_count counts nonnegative present integers; sales_cents sums those integers; refund_count counts negative integers; refund_cents sums them. Consequently processed=missing+sales_count+refund_count and net_cents=sales_cents+refund_cents. An invariant is a statement about a prefix, not a hope that the final answer looks plausible.
Initialization sets all six fields to zero, satisfying the empty-prefix definitions. A missing input increments processed and missing only. A nonnegative integer increments processed and sales_count and adds its amount to sales_cents; this includes a zero amount. A negative integer increments processed and refund_count and adds its negative amount to refund_cents. Each branch extends exactly one prefix category. For a finite input successfully exhausted, the prefix becomes the full input and the invariant supplies the requested totals. Rejected input raises instead of returning a falsely complete report.
Worked trace and two different means
For [1200, None, 0, -200, 500], the six-field states are (1,0,1,1200,0,0), (2,1,1,1200,0,0), (3,1,2,1200,0,0), (4,1,2,1200,1,-200) and (5,1,3,1700,1,-200). The net is 1500 cents over four present observations, giving a present-record mean of 375 cents. The sales-only mean is 1700/3 cents; it answers a different question because refunds are excluded from its numerator and denominator. Keeping an exact Fraction in the laboratory separates calculation from display rounding.
The empty stream and an all-missing stream have no present-record arithmetic mean. Return None for that absence. A stream containing one measured zero has a defined mean of zero. A refund-only stream has a present-record mean but no sales-only mean. These cases distinguish absence from a valid value; a successful calculation on a positive-only example cannot establish them. A filter based on if amount discards valid zeroes. For [0,600,None], it reports 600 rather than the correct present-record mean 300.
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.
Failure does not rewind an iterator
A function that keeps its accumulator local can fail without returning a report or changing an input list. That does not roll back consumption of a generator. For iterator [100,'invalid',500], the consumer has already obtained the first two elements when type validation raises; its next unconsumed value is 500. A second call cannot reconstruct the original input from that exhausted prefix. Specify whether retry requires a replayable source, a fresh iterator or durable input offsets. The laboratory demonstrates consumption directly and performs no external publication.
Independent transfer: change the reporting question
Use [0,None,-300,600,600]. Derive every six-field prefix, the net, the sales-only mean and the present-record mean. Split after the second element, summarize each chunk separately and merge them. Explain why a raw average of chunk means cannot replace the merged counts and sums. Then make the same split using a one-shot iterator and insert 'invalid' before the final 600. Predict what is consumed when validation raises, and state what a safe retry would require. Finally write a while-loop progress argument that includes the None branch. Attempt the exercise before opening the companion's reasoning; all practice remains optional.
Compare the complete transfer reasoning
The prefix states are (1,0,1,0,0,0), (2,1,1,0,0,0), (3,1,1,0,1,-300), (4,1,2,600,1,-300) and (5,1,3,1200,1,-300). Net is 900 cents. Three sales sum to 1200, so their mean is 400 cents; four present records sum to 900, so their mean is 225 cents. The first chunk has one present zero and one missing input; the second has three present inputs. Add their counts and sums to recover the same final state. Averaging chunk present means (0 and 300) would give 150 and ignore the unequal sample sizes. With invalid input inserted before the final 600, the iterator has already yielded 0, None, -300, 600 and invalid; the remaining 600 is not a replay of the whole record. Recreate or otherwise replay the input under an explicit retry policy. In the finite-sequence while loop, advance index for every successfully processed input, including None, and use len(rows)-index as a strictly decreasing nonnegative measure.
Run the complete laboratory
Copy to loop_lab.py and run python loop_lab.py with Python 3.10 or newer, using python3 if appropriate. Eight groups test actual transitions, exact means, prefix invariants, partition merges, equivalent while execution, invalid types, one-shot consumption and minimal counterexamples.
Source SHA-256: 1162c8076778584461db8a204c4c281fe48843461e26afc92fcfb26c0e198e6d
Complete Python source and executable tests
Primary reference study
- Python tutorial: for, range, break and continue
- Python built-ins: iter, next, enumerate and sum
- Fraction: exact rational calculations
- dataclasses: the laboratory named-state representation
The full assigned beginner chapters, documentation and prior teaching remain part of the course. This targeted native-guide and laboratory expansion does not establish full-source acceptance for unit 2 or whole-course acceptance.