Sometimes you need to exit a for or while loop without waiting for the normal
termination. There are two special Python branch
statements that do this:
If you execute a break statement
anywhere inside a for or while loop, control passes out of the loop
and on to the statement after the end of the loop.
A continue statement inside a for loop transfers control back to the top
of the loop, and the variable is set to the next
value from the sequence if there is one. (If the
loop was already using the last value of the
sequence, the effect of continue is
the same as break.)
Here are examples of those statements.
>>> i = 0 >>> while i < 100: ... i = i + 3 ... if ( i % 5 ) == 0: ... break ... print i, ... 3 6 9 12
In the example above, when the value of i
reaches 15, which has a remainder of 0 when divided by 5,
the break statement exits the loop.
>>> for i in range(500, -1, -1): ... if (i % 100) != 0: ... continue ... print i, ... 500 400 300 200 100 0