Python break statement is used to terminate or stop the execution of a loop based on some condition.
As soon as the loop encounters break
keyword, it is terminated and the execution resumes from the first line after the loop.
break use case
Suppose there is a large list of names, a dictionary of student objects or a tuple of numbers and you are searching for a particular value in these collections.
Now if the element you are searching is found at the second position, why should you check all the other elements. In such a scenario, break
is used.
break
is also used to terminate an infinite loop explained later in this post.
Syntax
break
itself is a keyword in python. It does not have any parenthesis or arguments. Placing it will alone perform the required task.
Thus, syntax of break
is
break
break
can only be written in a loop. Writing it outside of a loop will raise a compiler error.
Control Flow
break
is written inside a loop. When the control finds break
, it terminates the loop at the same instant and starts executing the statements written after the loop.
Execution sequence of a loop with break
can be shown with below flow chart.
Remember that break
only exits the loop inside which it is written. For nested loops(loop inside another loop), the statements of the outer loop will still be executed.
break python for loop example
Below is an example of break
statement inside a python program. It contains a for loop which iterates over a list of programming languages. Aim is to search for “python” in the list.
# list of languages languages = ["java", "javascript", "C", "C++", "python", "R", "ruby", "Cobol", "Go", "Pascal", "C#", "VB", "PHP", "Swift" "Fortran", "Groovy", "Haskell", "Kotlin", "LINQ", "Objective-C"] # value to search search = "python" # iterate over languages for language in languages: print("Checking list item:", language) # compare if language == search: print(search,"found in list") # terminate loop break
Below is the output of the program
Checking list item: java
Checking list item: javascript
Checking list item: C
Checking list item: C++
Checking list item: python
python found in list
Look, as soon as it found the item in the list, the loop is terminated, thus saving unnecessary iterations.
break while loop example
break
statement can be used with any looping construct, be it for or while. Above example modified to run with while loop is given below.
languages = ["java", "javascript", "C", "C++", "python", "R", "ruby", "Cobol", "Go", "Pascal", "C#", "VB", "PHP", "Swift" "Fortran", "Groovy", "Haskell", "Kotlin", "LINQ", "Objective-C"] search = "python" count = 0 # iterate over list while count < len(languages): # get current list item language = languages[count] print("Checking list item:", language) # compare if language == search: print(search,"found in list") # terminate break # increment loop counter count += 1
Output is the same.
break in nested loop
As stated earlier, break
terminates only the loop inside which it is written. If there are more than one loop inside another loop, then break
will move the control out of its own loop. Example,
# outer loop for i in range(5): print("***** Outer loop count start *****:", i) # inner loop for j in range(10): print("Inner loop count", j) # check condition if(j == 1): print("##### Terminating inner loop #####") # terminate inner loop break print("***** Outer loop count end *****:",i) print("-----------------------------------")
Outer loop is executed 5 times. Inner loop is intended to run 10 times but it is terminated when the counter reaches 1 with break
.
Output of above program is
***** Outer loop count start *****: 0
Inner loop count 0
Inner loop count 1
##### Terminating inner loop #####
***** Outer loop count end *****: 0
———————————–
***** Outer loop count start *****: 1
Inner loop count 0
Inner loop count 1
##### Terminating inner loop #####
***** Outer loop count end *****: 1
———————————–
***** Outer loop count start *****: 2
Inner loop count 0
Inner loop count 1
##### Terminating inner loop #####
***** Outer loop count end *****: 2
———————————–
***** Outer loop count start *****: 3
Inner loop count 0
Inner loop count 1
##### Terminating inner loop #####
***** Outer loop count end *****: 3
———————————–
***** Outer loop count start *****: 4
Inner loop count 0
Inner loop count 1
##### Terminating inner loop #####
***** Outer loop count end *****: 4
———————————–
Output clearly shows that even after inner loop breaks, outer loop is executed completely.
Breaking infinite loop
Many times you do not know the condition till which a loop should be executed. For example, you might want to keep checking till a connection(to a database or network) is established.
As soon as the connection is made, execute some task. In such situations, the code which checks the connection may be placed in an infinite loop which is terminated as soon as connection is created. Example,
while True: # check database connection # ..... # if connected: break # save data
break and finally
If a break is enclosed between try-except-finally
block used for exception handling in python, then finally
block is executed before the loop is terminated. Example,
# list of languages languages = ["java", "javascript", "C", "C++", "python", "R" "ruby", "Cobol", "Go", "Pascal"] # value to search search = "python" # iterate over languages for language in languages: print("Checking list item:", language) # compare if language == search: try: print(search,"found in list") # terminate loop break except: print("Except block") finally: print("*** Finally block ***") print("Loop completed")
Output of above code is
Checking list item: java
Checking list item: javascript
Checking list item: C
Checking list item: C++
Checking list item: python
python found in list
*** Finally block ***
Loop completed
It shows that if break
statement is written between finally
, then finally
block is executed before the loop exits.
Hope this article was useful in explaining the concept of break
statement and its application in python. Click the clap if you found it helpful.