Sub topic 7
Common mistakes and how to avoid them
This chapter assumes you know variables and assignment, comparison and boolean operators, if statements with indentation, and basic print and input. It also assumes you have met while, break, and continue. Here we look at the mistakes that cause most while loop bugs, how to spot each one, and how to fix it.
The working model
A while loop checks its condition before every pass. If the condition is true, the body runs, and Python checks the condition again. The loop ends only when the condition becomes false or a break or return runs. Almost every bug comes from one of two things: the condition never becomes false, or the loop's state changes in a way you did not expect.
Mistake 1: forgetting to update the loop variable
The most common bug is a loop whose condition depends on a variable that the body never changes.
n = 3
while n > 0:
print(n)
# n is never changed, so this prints 3 foreverThe fix is to change the variable inside the body, in a way that moves it toward making the condition false.
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff")This prints 3, 2, 1, and then Liftoff.
Mistake 2: updating in the wrong direction
An update that exists but moves away from the stopping point is just as bad. Here n grows, so n > 0 stays true forever.
n = 3
while n > 0:
print(n)
n += 1 # bug: should be n -= 1When a loop does not end, ask two questions. What value makes the condition false? Does each pass move the state closer to that value?
Mistake 3: continue that skips the update
continue jumps straight back to the condition check. Any statement after it in the body is skipped, including your update.
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i is never incremented, so this loops forever
i += 1Here i starts at 0, which is even, so continue runs every time and i stays 0. The fix is to update before continue.
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)This prints 1, 3, 5, 7, 9. Notice that i now holds the value after the update. If you need the old value, adjust your condition or print logic accordingly.
Mistake 4: while True with no reachable break
while True is a valid way to write a loop that stops on an event. It becomes a bug when no path in the body leads to break or return.
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")This version is correct because the if has two ways to become true. The loop ends on the right password or on the third attempt. A common variation is to test only for the password, which traps the user in the loop if they never type it.
Mistake 5: expecting break to leave nested loops
break exits only the innermost loop that contains it. The outer loop keeps going.
A clean way to leave both loops is to put them in a function and use return.
def find_pair(nums, target):
i = 0
while i < len(nums):
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return i, j
j += 1
i += 1
return None
print(find_pair([2, 7, 11, 15], 9))This prints (0, 1). Note that j is reset inside the outer loop. If you move j = i + 1 outside, the inner loop starts from a stale value on the second outer pass and skips pairs.
Mistake 6: misreading the else clause
The else block on a loop runs when the condition becomes false, and it is skipped if break ran. It is not an "otherwise" for the loop body.
n = 7
d = 2
while d * d <= n:
if n % d == 0:
print(f"{n} is not prime")
break
d += 1
else:
print(f"{n} is prime")For 7, the loop ends without a break, so it prints 7 is prime. If the else seems to run at the wrong time, check whether a break actually happened.
A checklist for debugging a stuck loop
Press Ctrl+C to interrupt a loop that will not stop. Then work through these checks:
- Print the variables used in the condition at the top of the body.
- Confirm the condition can become false.
- Confirm every path through the body, including paths through
continue, changes the state. - For
while True, confirm at least onebreakorreturnis reachable. - For nested loops, confirm which loop each
breakbelongs to.
Exercise
This loop should print the odd numbers 1, 3, 5, 7, 9, but it never ends. Why, and how do you fix it? i = 1 while i < 10: if i % 2 == 0: continue print(i) i += 1
Show answer
When i becomes 2, the condition i % 2 == 0 is true and continue runs. That skips i += 1, so i stays 2 forever. Fix it by updating i before the check, for example by moving i += 1 to the top and starting i at 0, or by incrementing in both paths: use i += 1 before continue in the even branch. One working version is i = 0, then while i < 10: i += 1; if i % 2 == 0: continue; print(i).
Exercise
A password loop uses while True and contains only "if answer == 'secret': break". What can go wrong, and what small change prevents it?
Show answer
If the user never enters the right password, the loop never ends. Add a second exit condition, such as counting attempts and breaking when attempts == 3.