Break exits its innermost loop, continue skips to that loop’s next iteration, and loop else runs when the loop finishes without break.
Python break, continue and loop else: encode the stopping condition
Operation contract
The review scan skips inactive receipts and stops when it finds the first active overdue record. If no such record exists, its for-else branch returns None. The two paths distinguish a found match from normal exhaustion without retaining an extra flag. Input ordering determines which match is returned.
Failure and ownership boundary
An exception or return also prevents the else suite from running; else does not mean that every iteration succeeded. Break affects only the nearest loop. A while retry loop needs a bounded attempt count and an explicit exception policy rather than an open-ended condition. Python exceptions: translate an input error without hiding its cause and Python generators: lazy iteration does not make retained output free show other ways iteration can stop.
Working program
def first_overdue(receipts):
for receipt in receipts:
if not receipt["active"]:
continue
if receipt["days_late"] > 0:
matched = receipt["receipt_id"]
break
else:
return None
return matched
receipts = [{"receipt_id": "R-0041", "active": False, "days_late": 4},
{"receipt_id": "R-0042", "active": True, "days_late": 2}]
print(first_overdue(receipts))
print(first_overdue([]))
attempts = 0
while attempts < 3:
attempts += 1
print("bounded attempts:", attempts)Output
R-0042
None
bounded attempts: 3Costs and limits
The scan takes O(n) in the no-match case and O(1) extra state. This fixture assumes accepted record fields; it is not a record validator. If input is an unbounded iterator, a no-match scan can fail to terminate unless another budget is supplied.
Common Mistakes
- Loop else means no break, not no exception.
- A break inside nested loops exits only its own loop.
Connected lessons
Python conditions and loops: distinguish no value from an empty value, Python exceptions: translate an input error without hiding its cause, Python generators: lazy iteration does not make retained output free.
