Early search termination
Stop scanning as soon as a matching item is found.
Python · Const
break exits the nearest enclosing for or while loop immediately. It is a statement rather than a callable value.
break immediately exits the closest enclosing for or while loop. It can be used only within such a loop, and it also prevents that loop's optional else clause from running; cleanup in a crossed finally clause still executes.
breakbreak keyword.for or while loop.for loop, its control target keeps the value from the current iteration.else block does not run when break terminates that loop.finally block runs before control leaves the loop.break inside a function or class defined in the loop is not valid for the surrounding loop.for item in ["ready", "stop", "later"]:
if item == "stop":
break
print(item)Prints items until the first matching value, then exits the loop.
Stop scanning as soon as a matching item is found.
End polling or retry logic when a success condition occurs.
Leave an inner loop while retaining its current for target.
break do in nested loops?break exits the nearest enclosing for or while loop immediately. It does not exit multiple nested loops at once.
Follow-up: How can code exit two nested loops? Use a flag, return from a containing function, or raise and handle an exception; one break only targets the nearest loop.
break interact with a loop's else clause?A loop's optional else clause is skipped when the loop ends through break. The clause can therefore indicate that the loop completed without being interrupted by break.
Follow-up: What other exits skip the loop else clause? A return or a raised exception also prevents that clause from running.
for loop's control target after break?If a for loop ends through break, its iteration target retains the value from the iteration that was active when the statement ran. This allows code after the loop to inspect that value.
Follow-up: Does this apply to while loops? The documentation specifies this target-value behavior for for loops, not while loops.
continueforwhiletryfinally