Sub topic 3
Changing State So the Loop Can End
This chapter assumes you can assign variables, write comparisons and boolean expressions, use if statements with correct indentation, and call print and input. You have probably written a basic while loop already. The question here is why a loop stops, and how to write one so you can show that it will.
A loop ends only if something changes
A while loop evaluates its condition before every pass. If the condition is true, the body runs and the condition is checked again. The loop stops only when the condition is false at a check, or when break, return, or an exception leaves it.
Python never looks at your intent. It only re-evaluates the expression. If nothing the condition reads has changed since the last check, the result is the same and the loop continues. A terminating loop therefore needs two things:
- A condition that depends on some state: a variable, an object, or an external source such as a file or a clock.
- A body that changes that state, so the condition can eventually become false.
The shape is the same in almost every loop that counts or processes something:
- Initialize the state before the loop.
- Test the state in the condition.
- Update the state in the body.
Here is the smallest complete example:
count = 0 # initialize
while count < 5: # test
print(count)
count += 1 # update
print("finished with count =", count)This prints 0 through 4, then finished with count = 5. Remove count += 1 and the loop prints 0 forever, because count < 5 never changes.
Four common update patterns
Most terminating loops fall into one of these patterns. Recognizing the pattern tells you where the update belongs.
| Pattern | Typical condition | Typical update | Example use |
|---|---|---|---|
| Counter | `i < limit` | `i += 1` | Repeat a fixed number of times |
| Shrinking input | `n > 0` or `items` | `n //= 10`, `items.pop()` | Consume digits or a stack |
| Moving index | `i < len(data)` | `i += 1` or `i += step` | Scan a list manually |
| Convergence | `abs(error) > tolerance` | Improve the estimate | Numeric approximation |
Counter
A counter is the simplest case. The state is an integer that moves a fixed step toward a bound. Counting down works the same way and often reads more naturally when you want to run "while time remains":
remaining = 3
while remaining > 0:
print("T-minus", remaining)
remaining -= 1
print("Liftoff")Shrinking input
Here the state is the data itself, and each pass removes part of it. This function adds up the digits of a non-negative integer:
def digit_sum(n):
total = 0
while n > 0:
total += n % 10 # take the last digit
n //= 10 # drop the last digit
return total
print(digit_sum(2486))This prints 20. The loop ends because n //= 10 strictly reduces a non-negative integer until it reaches 0. Since n is a whole number and gets smaller on every pass, it must hit 0 after at most as many passes as the number has digits.
The same idea works for a list used as a stack: while stack: is true while the list has items, and stack.pop() removes one per pass.
Moving index
When you need to look at positions in a sequence and decide how far to advance, a while loop with an index lets the update vary. This function removes every occurrence of a value from a list, in place:
def remove_all(items, value):
i = 0
while i < len(items):
if items[i] == value:
del items[i] # the list shrinks, so i stays put
else:
i += 1 # only advance when nothing was removed
return items
print(remove_all([1, 2, 2, 3, 2], 2))This prints [1, 3]. The update here is conditional. It still makes progress on every pass, because each pass either increases i or shortens the list. If you wrote i += 1 unconditionally, the second 2 in a row would be skipped after the first deletion shifted it into the earlier position.
Convergence
Some loops do not count to a known end. They repeat until a measured error is small enough. Newton's method for square roots improves a guess on every pass:
def sqrt_newton(x, tolerance=1e-10):
guess = x / 2 if x > 1 else 1.0
while abs(guess * guess - x) > tolerance:
guess = (guess + x / guess) / 2
return guess
print(round(sqrt_newton(2), 6))This prints 1.414214. The state is guess, the update improves it, and the condition measures how far off it is. The termination argument here is mathematical rather than "an integer reaches zero", and it depends on the input being positive. For a negative x the error never gets below the tolerance, and the loop would run forever. Convergence loops need the extra care described below.
Showing that a loop terminates
For a loop you care about, you can reason about termination with a short argument. Find a quantity, sometimes called a variant, with these properties:
- It is an integer, or otherwise cannot decrease forever (for example, a non-negative whole number).
- It has a bound, such that the condition is false once the bound is reached.
- Every pass of the body moves it strictly toward that bound.
In digit_sum, the variant is n. It is a non-negative integer, the bound is 0, and each pass makes it smaller. In remove_all, the variant is len(items) - i. A pass that deletes shrinks len(items), and a pass that advances increases i, so the value falls either way. You don't have to write this proof out each time. But if you cannot name a quantity that moves toward the bound, you should look at the loop more closely.
Where the update goes
The update normally sits at the end of the body, but position matters when continue or an early branch is involved. continue jumps straight to the condition check and skips everything after it. An update placed after a continue is skipped on the passes that take it.
This is the classic bug:
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i is never incremented, so this loops forever
i += 1At i = 0 the test is true, continue skips i += 1, and the next check sees i = 0 again. The fix is to update before continue can run:
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)This prints 1, 3, 5, 7, 9. The update happens first on every pass, so every path through the body makes progress. The cost is that i has already been incremented when you use it, so the printed values are the post-increment ones. Choose the placement deliberately, and adjust your condition or starting value to match.
If you cannot move the update to the top, put the update inside each branch that continues, or restructure the body so the skip uses if and else:
i = 0
while i < 10:
if i % 2 != 0:
print(i)
i += 1This version prints the odd numbers 1 through 9 and avoids continue entirely.
Mistakes that stop the loop from ending
Forgetting the update
The body never touches the variable in the condition. This is easy to see when you scan the loop for an assignment to the variable it tests. It is harder to see when the update is inside a function call or a method you assumed would change something.
Updating in the wrong direction
n = 10
while n > 0:
n += 1 # wrong direction: n grows away from 0The condition looks for n to fall to 0, and the update pushes it up. Python raises no error here. Compare the direction of the update with the direction the condition needs.
Updating the wrong variable
i = 0
j = 0
while i < 5:
j += 1 # meant iThe loop is syntactically fine, and j changes, but i never does. A mismatch between the names in the condition and the names in the updates is a frequent cause, especially in nested loops with i, j, and k.
A step that can jump over the bound
If the condition uses != or == and the step is not 1, the state can skip the exact value you are waiting for:
n = 1
while n != 10:
n += 2 # 1, 3, 5, 7, 9, 11, ... never equals 10Prefer an inequality such as n < 10. An inequality still ends when the state passes the bound, so a step that overshoots does no harm.
Floating-point drift
Floats cannot represent most decimal fractions exactly, so repeated addition accumulates tiny errors:
x = 0.0
while x != 1.0: # bug: x is 0.9999999999999999 after ten additions of 0.1
x += 0.1This never ends, and x keeps growing. Using < instead would stop, but it would run an extra eleventh pass, because x is still slightly under 1.0 after ten additions. The reliable fix is to count with an integer and derive the float from it:
steps = 0
while steps < 10:
steps += 1
x = steps / 10
print(x)This prints 1.0. For convergence loops, compare against a tolerance rather than testing for equality. Also remember that for very large inputs a fixed absolute tolerance may be smaller than the spacing between representable floats, so the error can never fall below it. Use a relative tolerance or math.isclose in that case.
Changing a collection while iterating over it
Removing items from a list inside a for loop over that same list skips elements, because the iterator tracks a position that the removals shift. A while loop with an explicit index, like remove_all above, avoids this because you control the index. The price is that you must manage the update yourself.
When you cannot prove termination
Some loops have no simple proof that they end. The Collatz process takes a number, halves it if even, or triples it and adds 1 if odd, and stops at 1. It is conjectured to reach 1 for every positive starting integer, but no one has proved it. Real programs also wait on outside events, such as a network reply or a file that may never arrive.
For these loops, add an explicit safety limit and fail loudly when it is exceeded:
def collatz_steps(value, limit=1000):
steps = 0
while value != 1:
value = value // 2 if value % 2 == 0 else 3 * value + 1
steps += 1
if steps >= limit:
raise RuntimeError(f"no convergence after {limit} steps")
return steps
print(collatz_steps(6))This prints 8, from the sequence 6, 3, 10, 5, 16, 8, 4, 2, 1. Starting values of 0 or below never reach 1, so the guard raises RuntimeError instead of hanging. Choose the limit from what you know about the problem, and treat reaching it as a bug or a bad input, not as a normal result.
Debugging a loop that will not stop
If a program hangs, press Ctrl+C in the terminal. Python raises KeyboardInterrupt and prints a traceback that shows which line was running, which usually identifies the loop. Then do the following:
- Print the state variables at the top of the body, for example
print(i, n, len(items)), and run a few passes. If the numbers do not change, the update is missing or skipped. If they change in the wrong direction, check the sign of the update. - List every path through the body, including each
ifbranch and everycontinue. For each path, confirm that the state moves toward the bound. - Check that the condition tests the variable you update, and that the types behave as you expect, for example a string where you meant an integer.
Exercise
This loop is meant to print 1, 2, 3, 4, 5, skipping nothing, but it never ends. Give the reason and a one-line fix. i = 1 while i <= 5: print(i) i = 1 + 1
Show answer
The update i = 1 + 1 always assigns 2, so i never grows past 2 and the condition i <= 5 stays true. Replace it with i += 1 so the new value depends on the current one.
Exercise
A loop starts with n = 20 and uses while n != 0: with the update n -= 3. Does it end? What condition would make it safe, and why?
Show answer
It does not end. n takes the values 20, 17, 14, 11, 8, 5, 2, -1, -4, and so on, so it jumps over 0 and never equals it. Use while n > 0:, which becomes false as soon as n is 0 or below, regardless of whether the step lands exactly on 0.
Exercise
In digitsum, the loop uses while n > 0 and n //= 10. Name the variant that guarantees termination, and say what happens if you call digitsum(-5).
Show answer
The variant is n, a non-negative integer that gets smaller on every pass until it reaches 0. For -5 the condition -5 > 0 is false at the first check, so the body never runs and the function returns 0 without looping. The loop is safe for negatives, but the result is probably not what a caller wants, so you might take abs(n) first.