Next / Previous / Contents / TCC Help System / NM Tech homepage

6.6. Special branch statements: break and continue

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:

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