Sub topic 3
Common mistakes and how to avoid them
Assume you know variables, comparisons, Boolean operators, if statements, indentation, print, and input. A while loop is safest when each iteration clearly changes the state tested by its condition.
Common mistakes and how to avoid them
The most common bug is forgetting the update. If i never changes, the condition remains true forever:
i = 0
while i < 3:
print(i)
i += 1Be careful with continue. It skips the rest of the current iteration and checks the condition again. Put required updates before it:
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)This prints 1, 2, 4, and 5.
The `else` clause on a `while` loop
A loop’s else block runs when the condition becomes false. It does not run if break exits the loop.
n = 7
d = 2
while d * d <= n:
if n % d == 0:
print("not prime")
break
d += 1
else:
print("prime")The else clause is useful for reporting that a search finished without finding a match.
`break` and `continue` in nested loops
break and continue affect only the innermost loop containing them. To leave multiple loops after finding a result, return from a function:
def find_pair(numbers, target):
i = 0
while i < len(numbers):
j = i + 1
while j < len(numbers):
if numbers[i] + numbers[j] == target:
return i, j
j += 1
i += 1
return NoneWhen to use `while` and when to use `for`
Use while when repetition depends on an event or changing condition. Use for when processing each item in a collection or a known range. A for loop usually makes iteration updates automatic, reducing infinite-loop risk.
Reading input in chunks with the walrus operator
The assignment expression := assigns a value and tests it in one expression:
import io
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3):
print(chunk)The loop stops when read returns an empty string, which is false.
Exercise
Why must the increment occur before continue in the example?
Show answer
Otherwise the loop could repeatedly test the same value and never reach its ending condition.