Python: Break and Continue

The break statement, like in C, breaks out of the innermost enclosing for or while loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

for i in range(3,10,2):
   if i == 7:
     print("I encountered {}".format(i))
else: #This only executes if for loop runs all the way through
  print("I just exited")

One alternative to breaking is using return inner function and this can be quite useful when you are trying to multilevel return.

Detecting A Break

You can use the continue keyword to detect if a break occurred during your loop or not. An example will be the application below;

for x in range(5):
  for  y in range(7):
      if y == 3:
         break #break out of the inner loop
       This continue is a way to detect if we did not have a short stop during our loop and finished the loop process
    continue #The purpose of the continue is to  detect if we did not break out
  #Anything here will only executes if we broke out of the inner loop
  print("Yes, there was a break")

Multi-level break

There are certain situations that will require breaking out of  outter loop from inner loop and this, python does not support natively. You have couple of options as discussed in this stackoverflow thread; ranging from refactoring to functions  using ‘return‘ all the way to using extremes like exceptions.

Useful Links

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s