Last time we saw this little program to see if all words in a sentence begin with the letter p:
words = input().split()
all_ps = True
for w in words:
if w[0] != 'p':
all_ps = False
if all_ps:
print('All words start with p')
else:
print("Some words don't start with p")
It may have occurred to you: Once we find a non-p word, isn't a waste to keep checking more words? We already know the answer, so it would be best to stop.
We can do this using
the break
statement. When Python encounters a
break
statement, it immediately halts processing the
loop, skipping to the first statement after the loop.
Here, we have modified the above program simply by adding the
line “break
” after the
“all_ps = False
” line.
words = input().split()
all_ps = True
for w in words:
if w[0] != 'p':
all_ps = False
break
if all_ps:
print('All words start with p')
else:
print("Some words don't start with p")
After executing “all_ps = False
”,
Python reaches “break
”, and so it
immediately skips to the final if
statement without
examining any more words. So if the user types “peter
piper picked a peck of pickled peppers”, the program
would stop examining words once it got to the word a.
(When we say that break
exits the loop in which it is
found, it's important to remember what a loop is: A loop is a
statement that tells the computer to possibly repeat some code.
Python has two types of loops:
for
statements and while
statements.
An statement is not a loop, since the body cannot be
executed repeatedly.)
The break
statement tends to be particularly helpful
when we are processing user input. Recall our previous program
to read several numbers from the user until the user enters 0,
then todisplay the sum of those numbers.
total = 0
num = int(input())
while num != 0:
total = total + num
num = int(input())
print(total)
This program has two different lines to read a line from the user. Conceptually, though, these two instances aren't that different. The following is arguably a more intuitive approach.
total = 0
while True:
num = int(input())
if num == 0:
break
total = total + num
print(total)
I would note that many programmers detest break
statements, and so they would prefer the former approach.
Their rationale is that a break
can be hard to see in a
particularly large loop, making it harder to understand when the
loop might actually terminate.
However, many other programmers (including me!) feel that the
second approach expresses the intuitive process of
reading-then-adding more aptly, without needless duplication of
the “num = int(input())
” line.
If the case of nested loops, break
only exits the
innermost loop in which it can be found. Here's an example.
words = input().split()
for s in words:
found = '(none)'
for t in words:
if t < s:
found = t
break
print('{0}: {1}'.format(s, t))
Given the input “peter piper picked a peck”, the output is the following.
peter: a
piper: peter
picked: peter
a: (none)
peck: a
If break
exited all loops, then you'd expect
this program to stop without displaying anything on this input.
As it stands, the break
statement skips to the
print
line (without examining other values for t
)
before going on to the next value for s
.