Lawfare Academy

CS 101 — Programming Foundations with Python · Weeks 3–5

Control flow, iteration and loop invariants

Full teaching sequence and cumulative subject work

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.

A complete ledger pipeline with a falsifiable specification — primary material, constructed-response tasks, complete worked model and changed-case examination →

Iteration, invariants and partial failure

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.

Trace the complete reasoning
  1. After 1200 the state is count 1, total 1200. Missing None leaves the state unchanged.

  2. 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.

  3. The mean is 1500 / 4 = 375 cents. Filtering with if amount would exclude zero and incorrectly report 500 cents over three records.

  4. 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.

Independent transfer problem

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.

Compare the transfer solution

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.

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.

Study the mechanism

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 example

def accepted_total(amounts):
    total = 0
    count = 0
    for amount in amounts:
        if amount < 0:
            continue
        total += amount
        count += 1
    return total, count

assert accepted_total([1200, -300, 0, 800]) == (2000, 3)

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.

Check your understanding

What proves the running total covers all accepted records?

  1. The invariant extends from the processed prefix to the complete finite list
  2. The first record has a positive value
  3. A successful run on one example proves all input behavior
Answer and reasoning for every option

Correct: The invariant extends from the processed prefix to the complete finite list Initialization, preservation and termination establish the argument.

Reconsider: The first record has a positive value The first value says nothing about later branches.

Reconsider: A successful run on one example proves all input behavior Examples reveal defects but do not prove every case.

Transfer laboratory: Early returns and a broken accumulator

A programmer puts return total inside a for loop. The input [500, 700, -100] should include refunds. Predict the returned value and repair the invariant without changing the business rule.

Work through the full solution

The defective function returns 500 after its first iteration. Move return after the loop and initialize total once before iteration. The correct result is 1100. State the invariant: after k iterations total equals the sum of the first k records including refunds. Empty input returns zero. Do not “repair” the result by dropping negative values; that changes the specification rather than control flow.

Evidence of understanding

Explain the first divergent execution step, show the corrected total and retain empty/refund cases.

Complete on-site teaching readings

These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.

  1. 4. More Control Flow Tools · Python Software Foundation and Python documentation contributors
  2. Built-in functions · Python Software Foundation and Python documentation contributors

Open in My Learning to record progress →