Python Tutorial / Control Repetition with while, break and continue
A while loop repeats while its condition is true. break exits the innermost loop, while continue skips the rest of the current iteration; check that every path can update the state needed for termination.
Choose condition-based repetition
Use for when the items to process are already available. Use while when repetition depends on changing state or repeated input. while True is reasonable when its internal exit rule is explicit.
If state changes only below continue, some inputs may bypass the update and cause an infinite loop. Stop an unresponsive loop with Ctrl+C, then inspect whether the condition-changing statements actually run.
For the relevant APIs and platform requirements, see Python: compound_stmts.
Read amounts until the user quits
Save while_input.py as UTF-8 and run python while_input.py. Enter 3500, an empty line, -1 and q in that order.
total = 0
while True:
text = input("amount or q: ").strip()
if text == "q":
break
if text == "":
continue
amount = int(text)
if amount < 0:
print("skip negative")
continue
total += amount
print("total:", total)
Program output with typed input omitted:
amount or q: amount or q: amount or q: skip negative amount or q: total: 3500
Trace each input through the loop
q triggers break. An empty input triggers continue, but the next iteration calls input again, so the input state still changes. A negative number prints a message and is excluded from the total. This version assumes integers or q; abc still raises ValueError.
Interactive terminals echo input, so their layout differs from the output-only block above. When adding exception handling, keep the quit check before numeric conversion so that q remains a command rather than an invalid number.
Enter 10 → 20 → q and check the total 30, then rerun with abc. The version that assumes integer input raises a conversion error. For retries, wrap the int conversion in try, catch ValueError, explain the input rule and continue. Check q before attempting numeric conversion.
Understand the exit scope and test edge cases
break exits only the innermost loop. Leaving several nested loops requires an explicit state design or returning from a function. continue likewise advances only its own loop.
- Enter q first and verify a total of zero.
- Enter 0 and confirm that it is a valid amount rather than an empty string.
- Try uppercase Q: this code treats it differently from q. Decide which command inputs should be normalized before changing the rule.
A robust input loop should handle only expected conversion failures and should retain an obvious way to exit. The exception handling lesson develops that distinction.




