Chapter 6 Loop Statement
6.4 Break and Continue¶
break and continue are two statements that are associated with loops; they must be put in a loop body. When break is executed, Python finishes the loop by directly jumping out of the looping statement (e.g. while), executing any successing statements. When continue is executed, Python finishes the current loop iteration without executing the rest of the loop body, jumping back to the Boolean condition again. For example,
>>> i=1
>>> while i<3:
... print (i)
... break # jump out directly
... i += 1
... print ('done')
...
1
done
In the example above, the statement print (i) in the while loop is executed only once, because the first time the break statement is executed, the loop finishes. The final value of i is 1, since i+ = 1 is not executed.
An example for continue is shown below.
>>> i=1
>>> while i<3:
... i += 1
... continue # jump to while
... print (i)
... print ('done ')
...
done
>>> print (i)
3
In the example above, the statement print (i) in the while loop is never executed. This is because every time continue is executed, the rest of the loop body is skipped. However, the loop continues until the Boolean expression i < 3 is changed to False, as demonstrated by the ‘done’ message and the final value of i is 3.
The use of break and continue can sometimes make a program more intuitive to understand. A version of guess_break.py that uses break instead of a complex Boolean condition is:
# [guess_break.py]
import random
answer = random.randint(1, 100)
limit = 7
guesses = 0
while guesses < limit:
guess = int(input('Your guess is: '))
guesses += 1
if guess == answer:
print ('You win!')
break
else:
if guess > answer:
print ('Too large ')
else:
print ('Too small ')
print ('You lose.')
The main structure of guess_break.py is a loop that repeats for limit iterations, asking the user for a guess at each iteration. If the guess is correct, it prints the winning message and terminates the loop. Otherwise it prints out the corresponding hint message and the loop continues. If the loop finishes when the Boolean expression guesses < limit becomes False, the else statement block is executed, printing out the losing message.
The break and continue statements can also be applied to a for loop, with the same interpretation as in a while loop: the break statement terminates the loop, and the continue statement skips the rest of the loop body and starts the next loop iteration.
The example above contains two for loops over the range container object. In the first loop, when the first element in range container object is greater than 5, the loop terminates. In the second loop, whenever the current element is odd, the loop continues without it being printed.
© Copyright 2024 GS Ng.