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.
Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.
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.
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.
Read Boolean laws as parenthesized propositions
The complete assigned Conditionals chapter develops truth tables, branching, early returns, logical opposites, conversion and a charting exercise. Its section 5.4 presents algebraic laws in code-like notation. When testing such a law in Python, explicitly parenthesize each side of the claimed equality. Otherwise comparison precedence can change the question being executed. This orientation retains the original source while making the executable interpretation precise.
For example, the intended proposition is (x and False) == False for a Boolean x. Set x=False. The parenthesized left side produces False, and comparing it with False produces True. Without those parentheses, x and False == False is parsed as x and (False == False). The comparison produces True, then False and True produces False. The failed expression did not refute Boolean algebra: it tested a different expression. Print the intermediate results before changing the law or the expected answer.
The same discipline applies to commutativity and De Morgan's laws. For Boolean values p and q, test (p and q) == (q and p), and test (not (p and q)) == ((not p) or (not q)). There are four input pairs, so an exhaustive truth table covers this deliberately finite domain. It does not prove that arbitrary Python objects, repeated function calls or external actions may be rearranged freely. State the operand domain as part of the argument.
A truth value and an operator's returned value differ
Python's and and or short-circuit and return an operand. They do not always manufacture a bool. For example, 2 and 3 returns 3, while 3 and 2 returns 2. Both results are truthy, but they are different values. Similarly 0 or 17 returns 17, while 2 or 17 returns 2. This makes the idiom measured or fallback unsuitable when zero is a legitimate measurement. To replace only an absent None, use an explicit absence test.
Evaluation order is observable even with Boolean results. Suppose a synthetic probe raises an exception. False and probe() skips the call and returns False. probe() and False calls the probe first and raises. A rewrite that preserves a truth table over already computed Boolean values need not preserve a program's errors or effects. The supplied laboratory records which probes actually run; it does not send messages or invoke an external service.
Worked guard: establish a denominator before division
A report has total=42 cents, count=0 and a minimum mean of 10 cents. The condition count != 0 and total/count >= 10 returns False without dividing. Reversing the two operands raises ZeroDivisionError before the guard can help. A guard must precede the operation whose precondition it establishes. After type validation, a positive count also allows an exact integer comparison: total >= threshold*count. The laboratory uses this form to avoid rounding a quotient. For count 4, 42 >= 40 is True; for count 5, 42 >= 50 is False; for count zero the condition is False and no mean is invented.
State the ordered domain before replacing a logical opposite
The chapter's comparison-opposite examples presume values for which the relevant order comparison behaves as an ordinary ordered comparison. Floating-point NaN is an important boundary. With n=float('nan'), n>=100 is False, so not(n>=100) is True. But n<100 is also False. Therefore replacing the negation with the apparent opposite changes the result on this input. A rule that is valid over ordered finite numbers was extended outside its domain.
Reject NaN and infinities before interpreting a numerical threshold. Type conversion alone is insufficient because float('nan') successfully creates a float. The original delay classifier accepts only built-in int and float values, excluding bool; floats must be finite and all values nonnegative. Arbitrarily large Python integers remain finite integers and need not be converted to float merely to classify them. These are explicit synthetic-data rules, not an inference that every application must use the same policy.
Design a branch partition and test its boundaries
For a fictional report, delays below 100 milliseconds are fast; delays from 100 inclusive to 200 exclusive are standard; all larger finite nonnegative delays are slow. In an if/elif chain, the first branch captures [0,100). At the second branch, the first test is already false, so a test of value<200 captures [100,200). The final branch captures [200,infinity) within the validated domain. These bands are disjoint and exhaustive for accepted inputs.
At 99.9 the result is fast; 100 and 199.9 are standard; 200 is slow. Test values immediately below, exactly at and immediately above each cut. Testing only 50 and 250 misses both inclusion decisions. Validation occurs before all three branches: an invalid NaN must not fall through into slow merely because both less-than comparisons return False. A suite that visits every branch can still miss this input-contract defect.
Independent transfer and explained counterexamples
First evaluate the parenthesized law and the unparenthesized expression for x=True and x=False, recording the intermediate comparison. Next predict which of two probes runs for True or probe(), and explain whether swapping operands is justified. Then classify [99.9,100,199.9,200] under the stated bands and specify the response to NaN, -1, True and the text '100'. Finally decide whether a total of -5 over one present record meets a threshold of -6, and explain why count zero is a different case. Attempt the record before opening its reasoning. Practice remains optional.
Test the boundary of an iteration argument
Read the complete assigned Iteration chapter together with these original corrections. Its progression from state updates to nested traversal and numerical improvement complements the transaction-prefix investigation. The examples have different contracts: a proof for a fixed finite sequence does not prove termination for every numerical recurrence or input stream. A Python for loop also works with iterators whose length is not known in advance. The chapter's advice about choosing for or while is a useful design heuristic, rather than a restriction imposed by the language.
For a digit counter, normalize a built-in integer to its nonnegative magnitude before dividing. Define zero to have one decimal digit and exclude bool from this particular input contract. Start count=1 and repeat n//=10 while n>=10, incrementing count. For -240, normalization gives 240; the successive states are (240,1), (24,2), (2,3). At each loop head, the original magnitude is the current prefix followed by count-1 removed digits. While the guard holds, integer division strictly decreases n, so the loop terminates. Dividing a negative number directly is unsafe for this argument: -1//10 is -1 because integer division floors. The chapter explicitly asks the learner to discover and repair this case. A five-thousand-digit integer can be handled arithmetically without first converting it to a decimal string.
Repair the triangular-table endpoint
Section 7.19 defines print_multiples(n, high) with range(1, high+1), so its second argument is an inclusive column maximum. The later proposed edit print_multiples(i, i+1) therefore prints i+1 columns, rather than the i columns in the pictured triangle. Use print_multiples(i, i) with that definition. Keep the original source visible and distinguish this endpoint correction from a change to the multiplication rule.
For three rows the corrected result is [1], [2,4], [3,6,9]. The proposed extra-one call instead begins [1,2]. A row-length invariant makes the discrepancy clear: completed row i has i entries, column j contains i*j, and the diagonal entry is i*i. Through row h, the number of entries is 1+2+...+h=h*(h+1)/2. Check shape and values separately; a visually plausible table can contain a missing or duplicated boundary column.
A bounded experiment is different from a termination proof
For the chapter's positive-integer recurrence, an even n is replaced by n//2 and an odd n by 3*n+1, stopping at 1. Starting at 3 gives 3,10,5,16,8,4,2,1. A two-transition budget reaches 5; it has not reached the goal within that budget. This does not establish that the unbounded recurrence fails to terminate. Starting at 2**k has a direct argument: repeated halving reaches 1 in k transitions. Exhaustive results on a chosen finite set establish only those cases.
The laboratory returns both the visited values and a reached_one flag, and validates the domain before stepping. The remaining budget is a decreasing integer measure for the bounded program. It proves that this experiment stops even when no proof has been supplied for the unbounded mathematical process. A timeout, an exhausted budget and a counterexample to a mathematical conjecture are different conclusions.
Derive a numerical update and its limits
For a positive target m, seek a positive r with r*r=m. Newton's tangent update for f(y)=y*y-m is y_next=y-(y*y-m)/(2*y)=(y+m/y)/2. In exact arithmetic, subtract r and simplify to obtain y_next-r=(y-r)**2/(2*y). Thus any positive starting y produces an estimate at or above r after one step; the squared error explains rapid local improvement. This reasoning requires y>0 and m>0. It does not justify dividing by a zero starting estimate, using negative targets for a real-valued solver, or ignoring floating-point rounding.
The chapter's starting estimate n/2 and absolute step threshold illustrate the update but are not a general-purpose square-root contract. At n=0 the first division fails. At n=1e-20 the example stops near 0.0009765625, while the desired root is 1e-10: a small absolute change has not established small relative error. A tiny fixed stopping threshold has units and scale. Always ask what quantity is controlled and what failure should be reported if it cannot be achieved.
The complete educational implementation first converts its accepted built-in int or float input to a finite nonnegative float, excluding bool. Its mathematical target is that represented float; conversion can round a large integer. It handles zero directly. For positive input, frexp writes n=m*2**e with 0.5<=m<1. If e is odd, double m and reduce e by one, so e is even and 0.5<=m<2. Iterate on this moderate m, then rescale with ldexp(y,e//2). This avoids squaring the enormous original input or constructing a zero initial estimate for a tiny subnormal input.
Stop when abs(y*y-m)<=tolerance*m, with default tolerance 1e-14 and a positive finite iteration budget. In exact arithmetic, writing delta=(y*y-m)/m gives y/r=sqrt(1+delta). The relative root error is abs(delta)/(sqrt(1+delta)+1), bounded by abs(delta). Floating-point evaluation and rescaling introduce rounding, so this is a stopping diagnostic with independent numerical tests, not a formally certified interval or a guarantee of correctly rounded results on every platform. Exhausting the budget raises ArithmeticError. Use math.sqrt for normal application code; this solver exposes the reasoning for study.
Read the language references with a version and an effect model
The complete mapped control-flow tutorial and built-in reference include material beyond elementary loops. The retained reference snapshot contains version-3.15 additions, including frozendict, sentinel, compile's module keyword and changes to the default text encoding. Those entries are not evidence that these features exist on a Python 3.12 interpreter. The laboratory is tested on Python 3.12 and uses no such additions. Consult the matching versioned official reference, supply encoding='utf-8' explicitly for text files, and check a feature's version notice. Likewise map(strict=True) is newer than the supported 3.12 baseline; zip(strict=True), used here, is available there.
Function defaults are evaluated when the definition executes, so a default list is shared between calls. Use None and create a fresh list inside when independence is intended. A local assignment makes that name local to its function unless explicitly declared otherwise; separate calls have separate local bindings. A for loop does not create a separate block scope for an ordinary loop variable. Augmented assignment has type-specific behavior: for lists, += can change a shared object, while rebinding a name to a newly concatenated list has a different aliasing effect. Do not extend the chapter's integer-update shorthand into a universal statement about mutable objects.
all and any stop as soon as their answer is determined. With an iterator over [0,7,9], any consumes 0 and 7, returns True and leaves 9. On empty input all is True and any is False; neither result proves that observations were present. zip normally stops at the shortest input. strict=True detects unequal lengths when reached, but earlier pairs may already have been yielded and processed. Validation during iteration does not undo those effects. In a nested subject traversal, counting matching subject entries equals counting students only when each student's subject list contains at most one match. Use a per-student existence test when duplicate entries must still count one person.
Independent record: trace, repair, then change the claim
First produce the three corrected triangular rows and the state trace for decimal_digits(-240); explain why zero returns one. Next use start=3 and budget=2 for the stated recurrence, then change the budget to 7. State exactly what each result permits you to conclude. Finally, for n=1e-20 compare the chapter's absolute-step output near 0.0009765625 with the target root 1e-10. Derive the scaled residual test and predict what scaled_sqrt(2,max_steps=1) reports. For an iterator over [0,7,9], call any and then list on the remainder. For zip(['a','b'],[10],strict=True), describe the first yielded pair and the next request. Specify what changes if processing each pair writes externally. Explain each result before running the complete laboratory; all practice remains optional.
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.
Further complete record
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.
Further independent Boolean record
Complete record: compare (x and False) == False with x and False == False, for Boolean x. A call to probe() raises RuntimeError if evaluated. The delay classifier accepts finite nonnegative built-in int or float values, excluding bool: value < 100 is fast, 100 <= value < 200 is standard and value >= 200 is slow. The exact integer report guard is count > 0 and total >= threshold * count, after validating integer inputs and nonnegative count.
First evaluate the parenthesized law and the unparenthesized expression for x=True and x=False, recording the intermediate comparison. Next predict which of two probes runs for True or probe(), and explain whether swapping operands is justified. Then classify [99.9,100,199.9,200] under the stated bands and specify the response to NaN, -1, True and the text '100'. Finally decide whether a total of -5 over one present record meets a threshold of -6, and explain why count zero is a different case. Attempt the record before opening its reasoning. Practice remains optional.
Further independent iteration record
Complete independent record and contracts: For triangular rows, the helper uses columns range(1,high+1), so high is inclusive; row r should end at r*r. decimal_digits accepts built-in int excluding bool, sets n=abs(value) and count=1, then repeatedly performs n//=10 and count+=1 while n>=10. The positive-integer recurrence replaces even n by n//2 and odd n by 3*n+1, stops at 1 and allows at most budget transitions; return visited values and whether 1 was reached. The educational scaled_sqrt accepts a finite representable nonnegative built-in int/float excluding bool, handles zero directly, normalizes positive n to m*2**e with even e and 0.5<=m<2, starts y=1 and updates y=(y+m/y)/2. It returns a rescaled result only when abs(y*y-m)<=1e-14*m; if max_steps updates do not meet that condition it raises ArithmeticError. These are synthetic study rules.
First produce the three corrected triangular rows and the state trace for decimal_digits(-240); explain why zero returns one. Next use start=3 and budget=2 for the stated recurrence, then change the budget to 7. State exactly what each result permits you to conclude. Finally, for n=1e-20 compare the chapter's absolute-step output near 0.0009765625 with the target root 1e-10. Derive the scaled residual test and predict what scaled_sqrt(2,max_steps=1) reports. For an iterator over [0,7,9], call any and then list on the remainder. For zip(['a','b'],[10],strict=True), describe the first yielded pair and the next request. Specify what changes if processing each pair writes externally. Explain each result before running the complete laboratory; all practice remains optional.
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.
Further 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.
Further Boolean reasoning
For x=True, both expressions evaluate to True; for x=False, the parenthesized law is True while the unparenthesized expression is False. In the latter, False==False is evaluated before and. True or probe() does not evaluate the probe. Moving the probe to the left can run it and change the program’s errors or effects. The four valid delays classify as fast, standard, standard and slow. NaN and -1 violate the numerical contract and raise ValueError; True and the string 100 violate the type contract and raise TypeError. A negative total of -5 over one present record has mean -5, which meets the threshold -6. With count zero, a mean is undefined; enough_per_record returns False rather than dividing or fabricating an average.
Further iteration reasoning
The triangle is [1], [2,4], [3,6,9], with row lengths 1,2,3 and six total cells. After magnitude normalization, the digit-counter states are (240,1), (24,2), (2,3); zero skips the loop and keeps its one-digit convention. Direct negative division can reach the fixed point -1 and invalidate a decreasing-measure claim. The two-transition recurrence record is [3,10,5] with reached_one=False; the seven-transition record is [3,10,5,16,8,4,2,1] with reached_one=True. The first reports an exhausted budget, and the second establishes termination for that starting value, rather than all positive integers. The tiny-target example's relative error is approximately 9,765,624, despite its small absolute step. Scaling writes n=m*2**e with even e and m in [0.5,2); checking abs(y*y-m)/m controls a dimensionless residual. The exact root-error identity explains the criterion while independent tests assess floating-point behavior. For target 2 and a one-step budget, the implementation cannot meet the requested residual and raises ArithmeticError. any consumes 0 and 7 and leaves [9]. Strict zip first yields ('a',10), then raises ValueError because the second input is exhausted before the first. An external effect from the first pair is already observable; strict validation supplies no rollback. Prevalidate replayable data before publication, or specify an explicit staging/transaction policy for the external operation.
Check understanding
What proves the running total covers all accepted records?
- A successful run on one example proves all input behavior
Feedback
Examples reveal defects but do not prove every case.
- 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.
Further reading
Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.
Use the original worked investigations and optional changed-record models in this unit. Historical directions below are retained as source history and do not require publisher chapters.
- Learning with Python 3 — Conditionals
- Learning with Python 3 — Iteration
- 4. More Control Flow Tools
- Built-in functions
- Original Academy — loop invariants, termination, exact means and chunked reports
- Original Academy — Boolean laws, guards and input domains
- Original Academy — iteration boundaries and numerical stopping