The break statement is allowed only inside a loop body. When break executes, the loop terminates. If a loop is nested inside other loops, a break in it terminates only the innermost nested loop. In practical use, a break statement is usually inside some clause of an if statement in the loop body so that break executes conditionally.
One common use of break is in the implementation of a loop that decides whether it should keep looping only in the middle of each loop iteration:
while True: # this loop can never terminate naturally x = get_next() y = preprocess(x) if not keep_looping(x, y): break process(x, y)
The continue Statement
The continue statement is allowed only inside a loop body. When continue executes, the current iteration of the loop body terminates, and execution continues with the next iteration of the loop. In practical use, a continue statement is usually inside some clause of an if statement in the loop body so that continue executes conditionally.
Sometimes, a continue statement can take the place of nested if statements within a loop. For example:
for x in some_container: if not seems_ok(x): continue lowbound, highbound = bounds_to_test() if x<lowbound or x>=highbound: continue if final_check(x): do_processing(x)
This equivalent code does conditional processing without continue:
for x in some_container: if seems_ok(x): lowbound, highbound = bounds_to_test() if lowbound <= x < highbound: if final_check(x): o_processing(x)
Both versions function identically, so which one you use is a matter of personal preference and style.
The else Clause on Loop Statements
while and for statements may optionally have a trailing else clause. The statement or block under that else executes when the loop terminates naturally (at the end of the for iterator, or when the while loop condition becomes false), but not when the loop terminates prematurely (via break, return, or an exception). When a loop contains one or more break statements, you often need to check whether the loop terminates naturally or prematurely. You can use an else clause on the loop for this purpose:
for x in some_container: if is_ok(x): break # item x is satisfactory, terminate loop else: print "Warning: no satisfactory item was found in container" x = None