Sub topic 7
Common mistakes and how to avoid them
This chapter assumes you can already write a basic while loop, use break and continue, and read an if statement with comparison and boolean operators. It collects the errors that show up most often in real code. For each one you will see the symptom, the cause, and a fix.
Almost every while bug comes down to one question: what makes the condition false, and does every path through the body move toward that? If you can't answer that for a loop, the loop probably has a bug.
Mistake 1: never changing the state the condition reads
The condition is re-evaluated before every pass. If nothing in the body changes any value the condition depends on, the result never changes.
count = 0
while count < 3:
print("working")
# bug: count is never changed, so the loop never endsThe fix is to update the variable the condition tests:
count = 0
while count < 3:
print("working")
count += 1A quick check is to name the variable in the condition, then find the line in the body that changes it. If you can't find that line, add one.
Mistake 2: an update that `continue` skips
continue jumps straight back to the condition check. Any statement after it in the body does not run on that pass. If the update sits after the continue, some passes never advance the loop.
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i stays 0 and the loop never ends
i += 1There are two safe patterns. The first is to update before the continue:
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)The second is to rewrite the loop so nothing needs continue:
i = 0
while i < 10:
if i % 2 != 0:
print(i)
i += 1Both versions print the odd numbers from 1 to 9 (the second prints 1, 3, 5, 7, 9 as i takes the values 1 to 9). Whenever you add a continue, scan upward and downward in the body to confirm that every statement that must run on each pass is above it.
Mistake 3: an exact-match condition that the state can step over
Conditions such as != or == only stop the loop if the state lands exactly on the target. If it jumps past the target, the loop keeps going.
n = 10
while n != 0:
n -= 3 # 10, 7, 4, 1, -2, -5, ... never equals 0Use an ordering comparison when the state moves in one direction:
n = 10
while n > 0:
print(n)
n -= 3This prints 10, 7, 4, 1 and then stops, because -2 > 0 is false.
Mistake 4: comparing floating-point numbers exactly
Floats cannot represent most decimal fractions exactly, so they make poor loop counters.
total = 0.0
count = 0
while count < 10:
total += 0.1
count += 1
print(total == 1.0, total)This prints False 0.9999999999999999. A loop written as while total != 1.0: would never end. A loop written as while total < 1.0: would run an eleventh time.
Count with an integer and compute the float from it. If you must compare floats, use math.isclose.
step = 0
while step <= 10:
x = step / 10
print(x)
step += 1Mistake 5: off-by-one errors
An off-by-one error means the loop runs one time too many or too few. It usually comes from choosing the wrong comparison or the wrong starting value.
count = 1
while count < 5:
print(count)
count += 1This prints 1, 2, 3, 4. If you wanted 1 to 5, the condition must be count <= 5.
To check a loop, trace the first pass and the last pass by hand. Write down the value of the loop variable when the loop starts, when the body runs for the last time, and when the condition finally fails.
| Goal | Start | Condition | Update |
|---|---|---|---|
| Run exactly N times | `i = 0` | `i < N` | `i += 1` |
| Count 1 to N inclusive | `i = 1` | `i <= N` | `i += 1` |
| Count down from N to 1 | `i = N` | `i > 0` | `i -= 1` |
Mistake 6: a condition that is always true
Some conditions look right but can never be false. The most common form is mixing or with !=:
answer = ""
while answer != "y" or answer != "Y":
answer = input("Continue (y/Y)? ")Any string differs from at least one of "y" and "Y", so the whole condition is always true, even when the user types y. You want "not y and not Y", which you can write in two correct ways:
answer = ""
while answer.lower() != "y":
answer = input("Continue (y/Y)? ")answer = ""
while answer not in ("y", "Y"):
answer = input("Continue (y/Y)? ")A related mistake is while answer == "y" or "yes":. The second operand of or is the string "yes", which is truthy, so the condition is always true. Write the comparison out each time, or use in.
Another mistake is writing = where you meant ==. Python rejects while n = 3: with a SyntaxError, which is a gift, because it fails immediately instead of looping forever.
Mistake 7: changing a list while looping over its indexes
Removing items shifts every later item one position left. If the index still advances, the loop skips the item that moved into the current slot.
nums = [1, 2, 2, 3]
i = 0
while i < len(nums):
if nums[i] == 2:
nums.pop(i)
i += 1 # bug: advances even after a removal
print(nums)This prints [1, 2, 3]. After the first 2 is removed, the second 2 slides into index 1, but i has already moved on to 2. Advance the index only when you did not remove an item:
nums = [1, 2, 2, 3]
i = 0
while i < len(nums):
if nums[i] == 2:
nums.pop(i)
else:
i += 1
print(nums)This prints [1, 3]. For this particular task a list comprehension is simpler: nums = [n for n in nums if n != 2].
Mistake 8: expecting `break` to leave every loop
break exits only the innermost loop that contains it. In nested loops, the outer loop carries on.
i = 0
found = False
while i < 3:
j = 0
while j < 3:
if i * j == 2:
found = True
break # leaves only the inner loop
j += 1
if found:
break # needed to leave the outer loop too
i += 1
print(i, j)This prints 1 2. Without the second if found: break, the outer loop would continue and i would reach 3. Another option is to move the loops into a function and use return, which leaves every loop at once.
Mistake 9: `while True` with no reachable exit
while True is a normal tool, but it moves the stopping rule from the condition into the body. Every while True loop needs at least one break or return that some run of the program can actually reach.
while True:
text = input("Age: ")
if text.isdigit():
age = int(text)
break
print("Digits only, please.")
print("Age recorded:", age)Check three things:
- The
breakis inside anif, so it runs only on the event you care about. - The event can really happen. A test such as
if count == 5is useless ifcountis never updated. - Bad input has a path back to the top of the loop, as in the example above.
Mistake 10: relying on truthiness when zero or empty is valid
A bare while value: stops for 0, 0.0, "", None and empty containers. That is helpful when "empty" means "done", and wrong when a valid value can be falsy.
readings = [5, 3, 0, 8]
i = 0
while readings[i]: # stops at the 0, even though 8 follows
print(readings[i])
i += 1This prints 5 and 3 and then stops, because the third reading is 0. When you mean "until the index runs out", say so:
readings = [5, 3, 0, 8]
i = 0
while i < len(readings):
print(readings[i])
i += 1If you mean "until a value is missing", test for it explicitly with is not None.
A diagnosis flow for a loop that will not stop
When a program hangs, press Ctrl+C to raise KeyboardInterrupt. Python then prints a traceback that shows which line was running. After that, work through these questions.
Tools for finding the bug
The simplest tool is a temporary print of the state at the top of the body. Print every variable that appears in the condition, and compare what you see with what you expected.
n = 10
while n != 0:
print("n =", n)
n -= 3
if n < -10: # temporary guard so the demo ends
breakFor loops that you can't prove will end, such as a search that depends on data, add a step limit that fails loudly instead of hanging.
def collatz_steps(n, limit=10_000):
steps = 0
while n != 1:
if steps >= limit:
raise RuntimeError("did not converge")
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
return steps
print(collatz_steps(27))This prints 111. The limit does not change the result for valid input, and it turns a hang into a clear error if the code is ever changed incorrectly.
Summary of symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Program hangs with no output | No update to the condition variable | Add the update to the body |
| Hangs only for some inputs | `continue` skips the update | Update before `continue` |
| Counts past the target | `!=` or `==` stepped over | Use `<`, `<=`, `>` or `>=` |
| One pass too many or too few | Wrong comparison or start value | Trace the first and last pass |
| Never stops, even on valid input | `or` combined with `!=`, or a truthy constant | Use `not in` or `.lower()` |
| Items skipped when removing | Index advanced after a removal | Advance only when nothing was removed |
| Outer loop keeps running | `break` leaves only the inner loop | Use a flag or `return` |
| Stops too early on `0` or `""` | Truthiness used as the test | Compare explicitly |
Exercise
This loop should print 1, 2, 3, 4, 5 and then stop, but it never ends. Name the two mistakes and write a corrected version. i = 1 while i != 6: if i == 3: continue print(i) i += 1
Show answer
The first mistake is that continue runs when i == 3 and skips i += 1, so i stays at 3 forever. The second is that the loop prints 1 and 2 and then hangs, so it never prints 4 and 5. The != test is not itself the bug here, but <= is safer. A corrected version that prints 1 to 5 (including 3) is: i = 1, then while i <= 5:, then print(i) and i += 1. If you really want to skip 3, move i += 1 above the check: while i <= 5: then i += 1, if i == 4: continue, print(i - 1). The simpler version is to print inside an if i != 3: block and always run i += 1 at the end.
Exercise
What does this code print, and why? How would you change it so every 2 is removed? nums = [2, 2, 5, 2] i = 0 while i < len(nums): if nums[i] == 2: nums.pop(i) i += 1 print(nums)
Show answer
It prints [2, 5]. When the first 2 is removed, the list becomes [2, 5, 2] and i becomes 1, so the second 2 at index 0 is skipped. At index 1, the 5 is kept and i becomes 2. At index 2, the last 2 is removed and the list becomes [2, 5]. To remove every 2, increase i only in an else branch (else: i += 1), or use nums = [n for n in nums if n != 2].