When explaining ‘break’ I usually start with some context and explain that ‘break’ is optional. “It doesn’t let you do anything new. But it may let you write better code at times.” That stops absolute beginners from getting too flustered.
Then I go through the following:
First, a question: “You are about to leave the house. Make sure you have your keys with you. Being locked out isn’t fun. Believe me, I’ve been there. You systematically start looking for your keys. When do you stop looking?”
The answer I’m looking for is of course “Once I’ve found my keys”.
We start with some text
line = "Shall I compare thee to a summer's day. Thou art more lovely and temperate"
We want to find the first word which contains the letter ‘c’.
To keep it simple I’m not going to worry about punctuation marks and just split this up on every space
words = line.split()
Now let’s find the first word containing the letter ‘c’.
for word in words:
if 'c' in word:
print(word)
Output:
compare
So far so good. But did you really stop looking once you found your keys? Let’s see what happens if we look for the first word containing the letter ‘p’.
for word in words:
if 'p' in word:
print(word)
Output:
compare
temperate
Notice how this returns two words, not just the first one. You’ve found your keys, kept looking and left the house with two sets of keys. A waste of time.
Maybe we should do it this way:
found = False
for word in words:
if 'p' in word and not found:
print(word)
found = True
Output:
compare
That’s a little better. You’ve found your keys, continued looking, but ignored any other keys you spotted. Still a waste of time.
Let’s rewrite this using ‘break’
for word in words:
if 'p' in word:
print(word)
break
Notice how I’ve only added the word ‘break’ here. Let’s check the output.
Output:
compare
Success. You found your keys, immediately broke out of the search loop, and left the house with a single set of keys. No time wasted, no unwanted output. We no longer need the ‘found’ variable, and the ‘if’ statement is simpler again.
In short, as soon as a ‘break’ statement is executed, Python exits the loop.
This also works in ‘while’ loops. And you can use ’else:’ in combination with ‘break’. But I’ll leave that for another article.