Sometimes you need to exit a
while loop without waiting for the normal
termination. There are two special Python branch
statements that do this:
If you execute a
anywhere inside a
while loop, control passes out of the loop
and on to the statement after the end of the loop.
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
the same as
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
reaches 15, which has a remainder of 0 when divided by 5,
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