Sub topic 1
Repetition with Loops
A loop is one way to tell a program to repeat work. This chapter goes back over iteration on purpose. In later chapters, each part of a loop gets a counterpart in a recursive function: the starting values, the test that stops it, and the update step. If you can name those parts in a loop, converting between the two styles becomes mechanical.
Prerequisites
This chapter assumes you can already:
- Write and call functions in at least one programming language. The examples use Python.
- Use
forandwhileloops. - Work with basic lists or arrays.
- Read simple Big-O notation such as O(1) and O(n).
The Anatomy of a Loop
Every loop that computes a result has four parts:
- Initialization sets the loop variables before the first pass.
- Condition is a test checked before each pass. When it is false, the loop stops.
- Body is the work done on each pass.
- Update changes the loop variables so that the loop moves toward stopping.
The values of the loop variables at any moment are the loop state. The loop state is everything the computation needs to keep going. If you froze the program between two passes and wrote down the variables, you could restart the loop from that snapshot and get the same answer.
Here are all four parts in a short function:
def sum_list(values):
total = 0 # initialization
i = 0 # initialization
while i < len(values): # condition
total += values[i] # body
i += 1 # update
return total
print(sum_list([3, 1, 4, 1, 5])) # 14The loop state is the pair (total, i). Before each pass, total holds the sum of the first i elements. A statement that stays true before every pass is called a loop invariant. The invariant is the main tool for checking that a loop is correct. It holds at the start, because the sum of zero elements is 0. Each pass keeps it true. When the loop stops, i == len(values), so the invariant tells you that total is the sum of the whole list.
`for` Loops Versus `while` Loops
Python's for loop handles the condition and update for you. It walks over an iterable such as a list, a string, or a range. A while loop leaves all four parts to you.
def sum_list_for(values):
total = 0
for v in values:
total += v
return total
print(sum_list_for([3, 1, 4, 1, 5])) # 14| Aspect | `for` loop | `while` loop |
|---|---|---|
| Best fit | A known collection or a fixed count | Stopping depends on a computed value |
| Who manages the update | The iterator | You |
| Risk of an infinite loop | Low, as long as the iterable is finite | Higher, because you can forget the update |
| Typical examples | Summing a list, counting from 1 to n | Euclid's GCD, reading input until it ends, convergence loops |
Use a while loop when the number of passes is not known in advance. Euclid's algorithm for the greatest common divisor is a classic case:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6
print(gcd(17, 5)) # 1The loop state is (a, b). Each pass replaces the pair with (b, a % b). The loop stops because b shrinks every time and cannot drop below zero. A good habit for any while loop is to name a quantity that strictly decreases toward the stopping condition. If you can't name one, the loop may never end.
Loops Use Constant Extra Space
A loop reuses the same variables on every pass. sum_list keeps two variables whether the list has 5 elements or 5 million. Its extra space is O(1), and its time is O(n) because the body runs once per element. A later chapter compares this with recursion, where each pending call takes up memory of its own. For now, notice that a loop's memory use does not grow with the number of passes unless the body builds a growing structure on purpose.
Common Errors in Loops
Off-by-one boundaries
range(a, b) includes a and excludes b. Forgetting this is the most common loop bug.
def factorial_wrong(n):
result = 1
for i in range(1, n): # stops at n - 1
result *= i
return result
def factorial(n):
result = 1
for i in range(1, n + 1): # includes n
result *= i
return result
print(factorial_wrong(5)) # 24, which is wrong
print(factorial(5)) # 120
print(factorial(0)) # 1, because the loop body never runsCheck the empty case on purpose. factorial(0) returns 1 because range(1, 1) is empty, so the starting value is the answer. That starting value plays the same role as a base case in recursion, as the next chapter shows.
Forgetting the update
When a while loop never changes the variable its condition tests, it runs forever:
def countdown_fixed(n):
steps = []
while n > 0:
steps.append(n)
n -= 1 # without this line, the loop never ends
return steps
print(countdown_fixed(3)) # [3, 2, 1]Updating state in the wrong order
When the new values depend on the old ones, updating them one at a time can overwrite a value before it is used:
def fib_wrong(n):
a, b = 0, 1
for _ in range(n):
a = b # old a is lost here
b = a + b # uses the new a, not the old one
return a
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b # both right-hand values are computed first
return a
print(fib_wrong(5)) # 16, which is wrong
print(fib(5)) # 5Python's tuple assignment evaluates the whole right-hand side before assigning anything. In languages without it, use a temporary variable. This matters later: converting a recursive call into a loop means updating several parameters at once, and they must all be updated together.
Changing a collection while looping over it
Removing items from a list while a for loop walks over it shifts the remaining elements, so some get skipped:
def remove_evens_wrong(values):
for v in values:
if v % 2 == 0:
values.remove(v)
return values
def remove_evens(values):
return [v for v in values if v % 2 != 0]
print(remove_evens_wrong([2, 4, 6, 7])) # [4, 7], which is wrong
print(remove_evens([2, 4, 6, 7])) # [7]Build a new collection instead, or loop over a copy such as values[:].
Loop State as the Bridge to Recursion
Every loop in this chapter keeps its state in a small set of variables, and each pass maps the old state to a new one:
| Loop | State | One pass maps | Stops when |
|---|---|---|---|
| `sum_list` | `(total, i)` | `(total + values[i], i + 1)` | `i == len(values)` |
| `gcd` | `(a, b)` | `(b, a % b)` | `b == 0` |
| `fib` | `(a, b, count)` | `(b, a + b, count + 1)` | `count == n` |
A recursive function can carry the same state in its parameters instead of in variables that get reassigned. The stopping test becomes the base case, and the state update becomes the arguments of the recursive call. Keep this table in mind for the chapters on accumulators and on converting tail recursion into loops.
Exercises
Exercise
The function below should return the sum 1 + 2 + ... + n, but total_to(4) returns 6 instead of 10. Find the bug and state the loop invariant of the fixed version. Code: def total_to(n): total = 0; for i in range(n): total += i; return total
Show answer
range(n) produces 0 through n - 1, so n itself is never added. Use range(1, n + 1). Invariant: before the pass that adds i, total equals 1 + 2 + ... + (i - 1), which is (i - 1) * i / 2.
Exercise
Write a while loop that returns the number of digits in a positive integer n (for example, 4 for 2026). Name the loop state and the quantity that decreases toward stopping.
Show answer
count = 0; while n > 0: n //= 10; count += 1; return count. The loop state is (n, count). n strictly decreases because integer division by 10 shrinks any positive n, and the loop stops when n reaches 0.
Exercise
In a language without tuple assignment, rewrite the update a, b = b, a % b from gcd so that it stays correct.
Show answer
Use a temporary variable: t = a % b; a = b; b = t. Computing a % b before overwriting a keeps the old value of a available for the calculation.