Introduction to Break Statement in Python
Break statement in Python is used as a loop or control statement in order to manage the code control flow direction in the execution order. The control statements commonly used in python programming are Break, Continue and Pass, where Break is used for ending the loop and moving the execution control to the next step of the code, Continue is used for skipping the specific steps and continuing the code execution, and finally Pass is used for passing some definite code statements.
Python supports below loop control statements:
- Break: Terminated the flow of the loop statement and executes the next statement outside the loop.
- Continue: It is used when we need to skip the execution of the remainder of statements in the loop and continue from the start.
- Pass: It is used when we need some statements syntactically, but do not want to put any statements.
This statement is used to terminate the flow of execution of loops in a program. The flow can also be diverted to different statements or different loop. A break statement can be used in the situation where we need to exit a loop (while as well as for loop)when one of the events get triggered. When a BREAK statement gets triggered in an inner loop, the flow of execution if diverted to the next statement in the outer loop.
Below is the sample old code style for breakout functionality:
for in range(10);
for j in range(10):
# instead we can try below code directly instead of calling function
for in range(10);
for j in range(10):
continue # this will be executed if the loop ended normally (no break)
break # this will be executed if 'continue' was skipped (break)
In the above code, we are defining a function for returning product of numbers. And if the product of two numbers is greater than 50 then end. Instead of using return in previous old logic we can use a break and continue indirect code rather than defining a function and calling it. Thanks to breaking statement feature which easily out this breakout work from the loop. It terminates the loop and continues with the execution of further statements. If we consider an example of searching for an element in an array, where we run a loop for parsing and then matching with the search element. Once the element is found we can exit the loop with a message as “element is found” using the break statement. Also in the nested loop, we can use the break statement to stop the execution of the innermost loop by specifying any conditions and then continue with the outer loop execution.
We need to just write ‘break’ after the condition that should be true to terminate the flow of execution.
How do you Write a Break Statement?
The Break Statement is a simple statement that holds the power of terminating the normal flow of the group of statements. Let us think of a simple scenario of a game say, subway surfer. Its working is not that much difficult. When one person starts the game it enters a long and never-ending infinite loop. While moving in a loop the objects being displayed are continuously changing. On every stage, it takes your input according to the objects being displayed eg – if currently, a bridge comes which you need to cross. Now every move you will make will be checked against various conditions or checks that have been applied .in the game.
In all these checks there is also one crucial check which decides if u r still in the game or not.eg –u need to jump and u don’t. Then the quit condition fails and the loop gets broken and u r out of the game. This quitting work is done by the ‘break’ statement. It becomes active when the check or condition mentioned becomes true.
For writing a break statement. Following things are needed:
1. Quit or End condition: It is also known as hault condition which must be satisfied for the execution of break statement.
for I in a;
print ‘Found a number in the list’
Explanation: The above code prints all the alphabets present on the list. In case it finds the first numeric in the list, break statement gets executed and break the loop and print ‘Found a number in the list’ ‘
2. The loop: The break statement is always used in a loop. It is meaningless in case we don’t use any loop Because it is meant to break the repeated sequence of the statement, which is only present in a loop.
Flow Diagram for Break Statement in Python
Below is the flow of how the break statement works in a program.
The working of break statement in the loop is shown below in for loop and while loop :
The program continues with the normal execution of the program. In case it faces a conditional code while executing a loop, and the output of the condition is true, then the flow redirected from its normal flow to the first next statement after the loop. In case the condition happens to be false, the loop does execute in the same manner.
Loops for Executing Iterative Statements
Python allows below loops for executing Iterative statements in a program
1. WHILE LOOP
The while loop executes the group of statements in sequence continuously until a stop condition is not fulfilled.
Eg: In the below program, there is an infinite loop that gets triggered always as while(1) is an always true condition. But we have declared a break statement that will be executed when the condition given in the “IF” statement will be true. And after that the just next statement after the loop will get executed.
Print “We are in the loop”
print ”Here break statement works”
print “I am out of the loop”
2. FOR LOOP
A FOR loop is used to iterate over a sequence like range, list, tuple, dictionary or string.
For I in [sequence]:
for I in a:
print “We are in loop with”
print ”Here Break statement is triggered”
print ”We are outside the loop”
Examples of Break Statement
Below are the examples of break Statement:
In the below example we are trying to search 8 from the array of numbers defined below using for loop.
# program to search 8 from array of numbers
for num in [1, 19, 8, 0, 9, 30, 29]:
# if number is 8 print message as found and break the loop
print("number 8 is found")
In the above program, we have an array of numbers that we have parsed using the for loop. Then we have included an if condition where we are checking if the “num” is 8 then break. Print the message else continue with the loop. When the “num” is 8 it satisfies the condition and the break statement is executed.
In the below program we are finding the sum of first five integers using break-in for loop :
# Declare the tuple num , sum temporary variable, and the counter
num = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0
counter = 0
# parsing the tuple
for i in num:
sum = sum + i
counter = counter + 1
if counter == 5:
print("Sum of the first",counter)
print("integers is: ",sum)
In the above program, we have a tuple declared as “num”, a variable to sum “sum” and a counter variable “counter”. Then using for loop we are parsing the tuple i.e for each element we add to the “sum”, also we increment the “counter”. If the counter reaches 5 we break the loop. Finally, we are calculating the sum of the first five integers.
In the below example we are trying to search 9 using the while loop.
# program to search 9
i = 0;
# While condition
if i == 9:
# break if 9 is found
print("out of loop");
In the above program, we are performing search functionality using while loop in python. By looping on the integers we have declared a temporary variable i which we are incrementing by one on each iteration. Inside the loop, we are checking if the “i” value is 9 then the break statement is executed. Finally, we output as integers from 0 to 8.
In the below program we are finding some of the first five integers using a while loop.
# Declare the variables sum and the counter
sum = 0
counter = 0
sum = sum + counter
counter = counter + 1
if counter == 5:
print("Sum of the first ",counter)
print("integers is: ", sum)
In the above program, we have declared the variables “sum” and the counter to increment the loop on the first 10 integers. We running a while loop on the condition where the counter should be less than 10. Inside the loop, we are calculating the sum of the first five integers. For the same we are declaring the condition if “counter==5” then break statement is executed.as a result we get the output as the sum of the first five integers.
In the below program we are making use of break statement in the nested loop:
# Array of Number
num = [1, 2, 3] # Array of Character
str = ['y' ,'x', 'z'] # outer loop
for i in num:
print("Number of items: " ,i)
# inner loop
for j in str:
if j == 'z':
print(" String of items: " ,j)
In the above code, we have declared an array of numbers “num” as 1,2,3 and an array of characters as y,x,z. We parse the array of numbers as the number of times we want the inner loop to be executed. Then inside the outer loop, we are looping on the array of characters.where we are displaying all the characters other than “z” from the array. Each time when the character is equal to “z” the inner loop on the array of character breaks and flow continues with the outer loop.and once again inner loop logic is initialized and executed.
Below example is an use-case of finding first leap year from 2000 to 2005
# parsing through the year from 2000 to 2005
for year in range(2000,2005):
#checking whether the year is leap year or not
if year%4==0 and year%100!=0:
print("year is first leap year" ,year)
In the above example, we used the function range to parse through the years using for loop and inside the loop, we are checking if the year is a leap year or not. Condition for the leap year is that year should be evenly divisible by 4 and it should not be evenly divisible by 100. If the year satisfies this condition then we break the loop using a break statement and print the message that the year is the first leap year.
In the below example we print all the prime numbers between the range 0 to 20:
for n in range(0, 20):
# Since all the prime numbers are always greater than 1
if n> 1:
for i in range(2, n):
if (n % i) == 0:
In the above code, we are running a loop on range from 0 to 20. Then as we know that all prime numbers are greater than 1, so if the num>1 then we are checking if the number has other factors also. By running a loop from 2 to the num we can check if num is divisible by any number other than 1 and itself.if so we are giving the break statement which will exit the flow. Else it will print the number itself.
The Break Statement in Python is a loop control statement that terminates the normal execution of a sequence of statements in a loop and passes it to the next statement after the current loop exits. This can be used in many loops – for, while and all kinds of nested loop.
This is a guide to Break Statement in Python. Here we discuss Introduction to Break Statement in Python along with Code Implementation and Output. You can also go through our other suggested articles to learn more –
- Destructor in Python with Advantages
- Introduction to If Statement in Python
- Python Features | Top 15 Features
- String Array in Python With Methods
- Guide to Destructor in PHP
- If Statement in Matlab with Examples
- Guide to Switch Case in PowerShell
- Guide to Continue in PHP
- Learn the Prime Numbers in Python