Python offers several statements for more subtle loop control. The point of these statements is to permit two common simplifications of a loop. In each case, these statements can be replaced with if statements; however, those if statement versions might be considered rather complex for expressing some fairly common situations.
The break statement terminates a loop prematurely. This allows a complex condition to terminate a loop. A break statement is always found within if statements within the body of a for or while loop. A break statement is typically used when the terminating condition is too complex to write as an expression in the while clause of a loop. A break statement is also used when a for loop must be abandoned before the end of the sequence has been reached.
The continue statement skips the rest of the loop's suite. Like a break statement, a continue statements is always found within an if statement within a for or while loop. The continue statement is used instead of deeply nested else clauses.
Examples break and continue. Here's an example that has a complex break condition. We are going to see if we get six odd numbers in a row, or spin the roulette wheel 100 times.
We'll look at this in some depth because it pulls a number of features together in one program. This program shows both break and continue constructs. Most programs can actually be simplified by eliminating the break and continue statements. In this case, we didn't simplify, just to show how the statements are used.
Note that we have a two part terminating condition: 100 spins
or six odd numbers in a row. The hundred spins is
relatively easy to define using the range function.
The six odd numbers in a row requires testing and counting and then,
possibly, ending the loop. The overall ending condition for the loop,
then, is the number of spins is 100 or the count of odd numbers in a row
is six.
Example 8.1. sixodd.py
import random
oddCount= 0
for s in range(100):
lastSpin= s
n= random.randrange(38)
# Zero
if n == 0 or n == 37: # treat 37 as 00
oddCount = 0
continue
# Odd
if n%2 == 1:
oddCount += 1
if oddCount == 6: break
continue
# Even
assert n%2 == 0 and 0 < n <= 36
oddCount = 0
print oddCount, lastSpin
![]() | We import the |
![]() | The for statement will assign 100
different values to |
![]() | Note that we save the current value of |
![]() | We'll treat 37 as if it were 00, which is like zero. In
Roulette, these two numbers are neither even nor odd. The
|
![]() | We check the value of |
![]() | We threw in an assert (see the next
section, the section called “The assert Statement”, for more
information) that the spin, |
At the end of the loop, lastSpin is the number of
spins and oddCount is the most recent count of odd
numbers in a row. Either oddCount is six or
lastSpin is 99. When lastSpin is 99,
that means that spins 0 through 99 were examined; there are 100 different
numbers between 0 and 99.