The break statement is used to terminate the loop when a certain condition is met. We already learned in previous tutorials (for loop and while loop) that a loop is used to iterate a set of statements repeatedly as long as the loop condition returns true. The break statement is generally used inside a loop along with a if statement so that when a particular condition (defined in if statement) returns true, the break statement is encountered and the loop terminates.
For example, lets say we are searching an element in a list, so for that we are running a loop starting from the first element of the list to the last element of the list. Using break statement, we can terminate the loop as soon as the element is found because why run the loop unnecessary till the end of list when our element is found. We can achieve this with the help of break statement (we will see this example programmatically in the example section below).
Syntax of break statement in Python
The syntax of break statement in Python is similar to what we have seen in Java.
break
Flow diagram of break
Example of break statement
In this example, we are searching a number ’88’ in the given list of numbers. The requirement is to display all the numbers till the number ’88’ is found and when it is found, terminate the loop and do not display the rest of the numbers.
# program to display all the elements before number 88 for num in [11, 9, 88, 10, 90, 3, 19]: print(num) if(num==88): print("The number 88 is found") print("Terminating the loop") break
Output:
11 9 88 The number 88 is found Terminating the loop
Note: You would always want to use the break statement with a if statement so that only when the condition associated with ‘if’ is true then only break is encountered. If you do not use it with ‘if’ statement then the break statement would be encountered in the first iteration of loop and the loop would always terminate on the first iteration.
Leave a Reply