break
and continue
StatementsThe break
and continue
statements alter a loop’s flow of control. Executing a break
statement in a while
or for
immediately exits that statement. In the following code, range
produces the integer sequence 0–99, but the loop terminates when number
is 10
:
In [1]: for number in range(100):
...: if number == 10:
...: break
...: print(number, end=' ')
...:
0 1 2 3 4 5 6 7 8 9
In a script, execution would continue with the next statement after the for
loop. The while
and for
statements each have an optional else
clause that executes only if the loop terminates normally—that is, not as a result of a break
. We explore this in the exercises.
Executing a continue
statement in a while
or for
loop skips the remainder of the loop’s suite. In a while
, the condition is then tested to determine whether the loop should continue executing. In a for
, the loop processes the next item in the sequence (if any):
In [2]: for number in range(10):
...: if number == 5:
...: continue
...: print(number, end=' ')
...:
0 1 2 3 4 6 7 8 9