Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 101 — Programming Foundations with Python
Weeks 3–5
Control flow, iteration and loop invariants
Learning objectives
- Explain and trace the mechanisms in control flow, iteration and loop invariants.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
A conditional chooses a branch; a loop repeats a transformation. Read indentation as part of the program's structure. A running total should be initialized once before the loop, updated inside it and returned after it. Moving initialization into the loop discards earlier work; moving return inside the loop stops after the first item. These are reasoning errors even when the program parses successfully.
A loop invariant describes what is true before and after every iteration. In the example, total is the sum of accepted values already processed, and count is how many such values there are. Initially both refer to an empty prefix. Processing a negative value changes neither. Processing an accepted value adds it and increments the count. Once the loop ends, the invariant covers the complete input. This is a small proof of correctness, not merely a demonstration on one convenient list.
Separate filtering policy from accidental behavior. Here negative amounts are excluded by an explicit rule. A real ledger might instead treat them as refunds; rejecting them would then corrupt the report. Empty input is another meaningful case. Computing an average requires either a defined response for count zero or an explicit error. Choosing a default zero average would falsely suggest an observed rate. Think about termination as well: a for loop over a finite list terminates, but a while loop must change state toward its exit condition. For each branch, identify which state changes and which remains constant.
Worked reasoning After 1200 the state is (1200, 1). The negative record is skipped. Zero contributes no money but does count as an accepted observation, giving (1200, 2). The final 800 produces (2000, 3). Division outside this function would produce 666.67 cents approximately, not 1000 cents: excluding zero from the denominator would answer a different question. Empty input produces (0, 0); the caller must handle the undefined mean.
Extended teaching and laboratory
An invariant states what an accumulator means after a processed prefix. For a validated transaction stream, total is the sum of accepted amounts and accepted is the number of accepted records. A useful invariant includes rejected records: skipping one must leave both accepted state variables unchanged. State is observable when an exception occurs, so a streaming consumer must decide whether a failure leaves a partial result or cancels the operation.
Do not conflate zero with missingness. Zero can be a valid measured amount; None can represent an absent measurement. A truthiness filter removes both and changes the denominator of a mean. This is a specification error even if the loop terminates and every arithmetic operation is legal.
Worked problem Process [1200, None, 0, -200, 500]. None is missing; negative values are valid refunds. Return count, total and mean of present records.
Step-by-step reasoning 1. After 1200 the state is count 1, total 1200. Missing None leaves the state unchanged.
- Zero is present, giving count 2 and total 1200. The refund gives count 3 and total 1000. The final amount gives count 4 and total 1500.
- The mean is 1500 / 4 = 375 cents. Filtering with if amount would exclude zero and incorrectly report 500 cents over three records.
- An empty or all-missing stream has count zero and no defined arithmetic mean. Return an explicit absence or a documented error; do not invent a zero mean.
Apply the idea
Process [1200, None, 0, -200, 500]. None is missing; negative values are valid refunds. Return count, total and mean of present records.
The policy changes: refunds must be reported separately while the sales mean excludes refunds but includes zero. Trace the same input and state the revised invariant.
Read the worked reasoning
Maintain sales_count, sales_total and refunds_total. The sales are 1200, 0 and 500: count 3, total 1700, mean 566⅔ cents. Refunds total −200 cents, so net remains 1500. After each prefix, sales_total sums nonnegative present amounts and refunds_total sums negative present amounts. A single net mean would erase the distinction the new report requires.
Check understanding
What proves the running total covers all accepted records?
- The invariant extends from the processed prefix to the complete finite list
Feedback
Initialization, preservation and termination establish the argument.
- The first record has a positive value
Feedback
The first value says nothing about later branches.
- A successful run on one example proves all input behavior
Feedback
Examples reveal defects but do not prove every case.
Further reading
Work the Boolean, branching and iteration examples before the transaction loop. Hand-trace empty, one-item and boundary cases, then implement the chapter exercises. Write a loop invariant in ordinary language and test a deliberately incorrect update. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.