|
The break and continue StatementsNormally, a loop only terminates when its conditional expression becomes false. To break out of a for or while statement in the middle of executing it, use break:
If you examine this code carefully, you will see that it now prints only the numbers from 1 to 5, as the break statement is executed when x is equal to 5. The continue statement tells Python to stop executing this iteration of the loop and start over again from the top. For example, this code prints the numbers from 1 to 10, but skips 5:
Notice the second x = x + 1 statement, just before the continue. If it is not there, the loop will never get past 5, and will run forever. (Loops that run forever are sometimes called infinite loops.) |