Iteration Boundaries and Numerical Stopping

Original explanations, worked corrections and independent practice accompanying the retained assigned sources. These synthetic experiments are 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.

Compare the independent 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.

Run and inspect the complete implementation

Save as iteration_lab.py and run python iteration_lab.py. Tested on Python 3.12. Eight groups include independently calculated table shapes, negative/zero digit cases, bounded recurrence traces, reproduced source-example failures and Decimal/standard-library numerical comparisons. These tests do not establish formal numerical certification or full-course acceptance.

Source SHA-256: ae783cbc1ceb7c922c6f57bf9bf9554a23a1895cf8c01087ffa74dc5083569a5

Complete Python source and executable tests

Source locators

Earlier source text, attribution and editions remain available. No publisher endorsement or university affiliation is implied. Turtle pictures were inspected during source review; this is not a claim that a turtle GUI was executed or that a physical mobile device was tested.