Next / Previous / Contents / Shipman's homepage

23.2. The break statement: Exit a for or while loop

The purpose of this statement is to jump out of a for or while loop before the loop would terminate otherwise. Control is transferred to the statement after the last line of the loop. The statement looks like this:


Here's an example.

>>> for i in [1, 71, 13, 2, 81, 15]:
...     print i,
...     if (i%2) == 0:
...         break
1 71 13 2

Normally this loop would be executed six times, once for each value in the list, but the break statement gets executed when i is set to an even value.