Figuring out if “break” was used to exit the loop in Python

In this short article let us see how we can figure out if the “break” statement was executed or not in the loop which has just been executed.

Let us have a look at an example.

# List containing 5 items
list1 = [1, 2, 3, 4, 5]

for i in list1:
    cmd = input("Command: ")
    if cmd == 'stop':
        break

# how to know if the break statement was executed or not here?

In the example above, python will get an input from the user in each iteration, and if the user enters the word “stop”, python will execute the break statement and exit from the for-loop.

The astute readers among you will have the following questions in your mind:

  1. How to figure out if the for loop exited because of the break statement or because it ran through all the items in list1 from 1 to 5?
  2. If it did exit the for loop, which value of list1 being used when the for loop was ended by the break statement?

Let us first see the answer to question#1 above.

Figuring out if break was executed or not

In software engineering, while dealing with situations like this, we implement something called a “Flag” to indicate that an “Event” has occurred

A good real-life analogy of flags and events will be, say you ran out of milk and you wish to remind yourself to buy more the next time you go grocery shopping. In that case, you can put up a sticky note on the fridge so that you know till that sticky note is present, then you need more milk!

So in that case

  • ran out of milk is the “event” and
  • the sticky note is the “flag”

In the programming world, the simplest way to implement these “Flags” is using Boolean variables. (A Boolean object can hold only 2 values: True and False)

In our example above, we can implement a simple Boolean flag as follows

# Boolean flag
stopPresentFlag = False

# List containing 5 items
list1 = [1, 2, 3, 4, 5]

for i in list1:
    cmd = input("Command: ")
    if cmd == 'stop':
        stopPresentFlag = True
        break


if stopPresentFlag == True:
    print ("Break statement used to exit loop")

Here stopPresentFlag is a Boolean object, initialized with False. Then in the for-loop, if the user has entered “stop” then we raise the stopPresentFlag (by setting it to be “True”) so that the rest of the program can easily check if the “break” was executed or not by looking at this flag.

Another way of doing this is just to check the value of the “cmd” object after exiting the loop as shown below.

# List containing 5 items
list1 = [1, 2, 3, 4, 5]

for i in list1:
    cmd = input("Command: ")
    if cmd == 'stop':
        stopPresentFlag = True
        break


if cmd == 'stop':
    print ("Break statement used to exit loop")

But this won’t work if the for-loop is implemented inside of another function, as all objects created inside a function are only visible inside that given function.

# List containing 5 items
list1 = [1, 2, 3, 4, 5]

def func1():
    for i in list1:
        cmd = input("Command: ")
    if cmd == 'stop':
        break

print(cmd)

Here I am trying to print the last command received outside the func1() function, but since the object was first declared inside the function, the value is not available outside of it and we end up getting the following error

NameError: name 'cmd' is not defined

We can work around this issue by making cmd a global object by initializing it outside any functions, but that is not considered to be good practice as this ‘cmd’ object is only useful inside the function.

Also instead of “stop”, if we have a string that is very long, then we will end up writing code that is not very readable!

Because of these reasons, we decided to go with the stopPresentFlag instead.

Next let us see how to figure out “when” the break statement was executed.

Figuring out when the break statement was executed

We can record what values our variables have while our code is executing by implementing something called “Status”, which are basically objects whose specific duty is to keep track of the program execution status.

Let us see how we can do this.

# Boolean flag
stopPresentFlag = False

# List containing 5 items
list1 = [1, 2, 3, 4, 5]

# Status
loopStatus = list1[0]

for i in list1:
    loopStatus = i
    cmd = input("Command: ")
    if cmd == 'stop':
        stopPresentFlag = True
        break

if stopPresentFlag == True:
    print ("Break statement used to exit loop at position ", loopStatus)

Let us run the code above and see what happens

Command: go
Command: go
Command: go
Command: stop
Break statement used to exit loop at position 4

As you can see, I gave “go” 3 times and the loop was executing fine. When I gave “stop”, the break statement was hit and the loop executed.

At that moment, the “loopStatus” variable had the value “4” stored in it and hence that value got printed out!

You can also make the code simpler by reading the value of “i” instead of making a new status variable loopStatus. But the same problem that we saw with the Boolean flag will happen again here as shown below.

i.e. if we implemented the for loop inside a function we won’t be able to access the object “i” outside of that function, hence we went with this approach instead!

I suggest you open your computer and try out all the examples above! Remember that our brain is like muscles, if you want to be a bodybuilder, you must spend lots of time in the gym doing hard exercises and if you want to be a programmer, you must spend more time practicing and solving coding problems!

And with that note, I will end this article!
I hope you had a great time reading the article!
If your thirst for knowledge has not been quenched yet, here are some more articles that might interest you!

Related Articles

Python “if” Statement with Multiple Conditions: Explained with Examples!
Python “if not”: Explained with Examples!
Python’s [:] Notation Explained with Examples!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn