Introduction
In the spirit of giving I thought I would write a blog to help one of friends out with his understanding of using the "break" statement in Python. Break, if you are not familiar with it is used in Python, as well as some other programming languages, to create a condition to end a loop. I personally find this exit most useful when using it in nested loops (one loop inside of another) because, it allows you to exit the inner loop once a condition is met and return to the outer loop which creates less iterations, therefore saving time.
for
Loop
If you are not very familiar with loops, a for
loop is used to iterate over a sequence, whether it be a list, dictionary, tuple or even just a string. To use break
in a for
loop the only you thing you need to do create a conditional statement with the "if" statement that defines what you want the program to recognize and then just let it know to break if that condition is met. So as a silly example lets create a simple loop that goes through the letters of my name, a string, and prints them one by one but stops when it finds the "o".
for letter in "timothy":
if letter == "o":
break
print(letter)
print("loop ended")
So above on the first line I initiated my for loop telling it to go through each letter of the string "timothy", then below inside of that loop, one tab further, I created a statement letting the computer know that if it found an "o" I wanted it to do something. Then it was a simple as placing the statement 'break' one tab in on the line below, so that it was inside the if statement, just letting the program know to end the loop once the condition was met. You can see that this worked because the loop ended before it once again hit the line with print(letter)
and instead moved to the print statement that is outside of the loop.
while
Loop
Executing a break
statement in a while
loop is done the exact same way and does the same thing. Though in my practice of using while
loops I have not needed to use a break
statement since the purpose of a while
loop is to repeat a statement as long as the given statement is true. Though I could potentially see the use of a break statement as an emergency exit by using it as a counter for iterations or time to prevent an indefinite loop that could end the statement early. For example if we ran the following code, the computer would keep printing the next number until we stopped the kernel or the program crashed.
n=0
while n > -1:
n+=1
print(n)
Though if we wanted to make sure this didn't happen, imagine a more complex code that we weren't sure if it would meet the requirement, we could add a simple counter with a break statement to make sure we only repeated a certain amount of iterations.
n=0
m=0
while n > -1:
n+=1
m+=1
if m == 10:
break
print(n)
Nested Loops
As I mentioned earlier using break
in nested loop can lead to running less iterations, so as an example I recreated a small version of my buddies problem to show how.
def reducedict(D, keywords):
result={}
for (key,value) in D.items():
for text in keywords:
if text.lower() in key.lower():
result.update({key:value})
break
return result
If we take a look at what this code is doing, we can see that the first for
loop is iterating through a dictionary and then below the second loop is looping through a list of keywords to see if any of them match the keys of the dictionary, to add the matching key with its value to a new reduced dictionary. So lets create a dictionary and list to see what happens:
dictionary ={"one":"happy","two":"sad","Three":"mad"}
numbers=("one","three","five")
reducedict(dictionary,numbers)
We can see that it was successful as it pulled out only the keys labeled "one" and "three" but, what did the break do? So if we did not have break
it would check each key in our dictionary once for each keyword. Though with our break
statement, since it is finding a matching keyword the first term it will return to the outer loop, skipping the remaining two iterations through the keywords and begin searching the next term in the dictionary. When timed I received 2.16 µs ± 63.1 ns per loop without a break
statement and 1.71 µs ± 22.5 ns per loop with it included. This may seem like a very small amount of time, and it is, but imagine searching through all two hundred seventy three thousand words in the Oxford dictionary with their full definition.
Conclusion
I know learning about coding can be tough and I am constantly learning about how small changes in your code can make huge differences. I know this blog will help at least one person, me, as I write it and I hope it helps others understand more about some complex topics. I would like to also add that on this topic, this is written to the best of my knowledge and if anyone has a correction, I would love to hear it!
Merry Christmas!
Top comments (0)