Sub topic 2
Leaving a Python `while` Loop Early
Assume you know variables, comparisons, Boolean operators, if statements, and indentation. A break statement exits the innermost loop immediately. Use it when an event should stop repetition before the loop condition becomes false.
Leaving a loop early with `break`
while True creates a loop whose condition never becomes false. The loop must therefore contain a break, return, or another way to stop.
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")Here, the loop stops when the password is correct or when the third attempt is used. The break statement skips any remaining statements in the loop body.
A condition-controlled loop is often clearer when the stopping rule is part of the condition. Use while True when the loop should continue until an event occurs inside its body.
flowchart TD
A[Start iteration] --> B[Read password]
B --> C[Increase attempts]
C --> D{Correct password or 3 attempts?}
D -- No --> A
D -- Yes --> E[break and continue after loop]Skipping an iteration with `continue`
continue skips the rest of the current iteration and starts the next condition check. Put required state updates before continue.
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)This prints the odd numbers from 1 through 9. The update happens before continue, so i still changes on every pass.
Compare these statements:
| Statement | Effect |
|---|---|
| `break` | Exits the loop immediately |
| `continue` | Skips to the next iteration |
A common error is placing the update after a possible continue:
i = 0
while i < 10:
if i % 2 == 0:
continue
i += 1Since i starts at zero and never changes, the condition stays true forever. Move the update before the branch, or redesign the loop so every path advances its state.
Exercise
What does break affect in a nested loop, and where should an update go when continue might run?
Show answer
break affects only the innermost loop. Put the required update before continue, or ensure every path updates the loop state.