Sub topic 1
Repetition with Loops
Every repetitive computation has to answer three questions. What state do you start with? When do you stop? How does the state change on each pass? A loop answers all three in plain view. This chapter sets up that model so you can compare loops with recursion in later chapters.
Prerequisites
This chapter assumes you can:
- Write and call functions in Python or a similar language
- Use
forandwhileloops - Work with basic lists
- Read simple Big-O notation such as O(n) and O(1)
The Three Parts of Loop State
A loop works through a few variables, called its loop state, that change on each pass. Every correct loop has three parts:
| Part | Role | Example |
|---|---|---|
| Initialization | Sets the starting state | `total = 0`, `i = 1` |
| Condition | Decides whether to run another pass | `i <= n` |
| Update | Moves the state toward the stopping point | `i += 1` |
A while loop writes all three parts out explicitly:
def sum_to_while(n):
total = 0 # initialization
i = 1
while i <= n: # condition
total += i # body
i += 1 # update
return total
print(sum_to_while(100)) # 5050A for loop over a range handles the counter for you. The range sets the start, stop, and step, so only the accumulating variable is left for you to manage:
def sum_to_for(n):
total = 0
for i in range(1, n + 1):
total += i
return total
print(sum_to_for(100)) # 5050When the Number of Passes Is Unknown
Use for when you know the sequence of values ahead of time. Use while when the stopping point depends on data you compute inside the loop. Counting digits is a typical case:
def count_digits(n):
count = 1
while n >= 10:
n //= 10
count += 1
return count
print(count_digits(0)) # 1
print(count_digits(12345)) # 5The update n //= 10 shrinks n on every pass, so n must eventually drop below 10. The loop always stops because each update makes progress toward the stopping condition. Keep this idea in mind. Recursive functions need the same guarantee.
Space Cost of a Loop
A loop reuses the same variables on every pass. sum_to_for(10) and sum_to_for(10_000_000) use the same few variables, so the extra space is O(1) and the time is O(n). Later chapters show that a recursive version usually needs O(n) space, because each call keeps its own copy of the state.
Common Errors
- Off-by-one bounds.
range(1, n)stops atn - 1. Check the first and last values the loop actually touches. - Missing or wrong update. If the update is missing, or moves away from the stopping condition, the
whileloop never ends. - Initializing inside the loop. Putting
total = 0inside the loop body resets it on every pass. - Changing a list while iterating over it. Adding or removing items from a list during a
forloop skips or repeats elements. Iterate over a copy, or build a new list.
Exercise
The function def product_to(n): result = 1; for i in range(1, n): result *= i; return result is meant to return 1 × 2 × ... × n. What does it return for n = 4, and how do you fix it?
Show answer
It returns 6, because range(1, 4) yields only 1, 2, 3. Change the range to range(1, n + 1) so that it includes n. Then it returns 24.
Exercise
Name the initialization, condition, and update in count_digits, and explain why the loop always terminates for a non-negative integer.
Show answer
The initialization is count = 1, along with the starting value of n. The condition is n >= 10. The update is n //= 10 together with count += 1. Integer division by 10 strictly decreases any n of 10 or more, so n must eventually fall below 10 and the condition becomes false.