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 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: This equivalent code does conditional processing without continue: for x in some_container: 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:
blog comments powered by Disqus |