Table of content

Break statement in python

In python, the break statement terminates the execution of the current loop when certain conditions are met and starts executing from the next statement.

In the nested loop the break statement will terminate the execution of the current loop, and the control of the program will pass to statements that come after the loop. The flowchart for the break statement is given below.
break-flow

Execution of break statement with for loop

Consider a for loop that iterates from a range of 1 to 10. In each iteration, it checks for if condition. If the condition is True break statement terminates the loop containing it and control comes out of the loop.

for num in range(1,10):
    if num == 4:
        break
    print("num is: ", num)

The output for the above code is given below.

num is:  1
num is:  2    
num is:  3

Execution of break statement with While loop

Let us consider a variable num, initialized to 3. The while loop executes if the value of num is not equal to 0. In each iteration of the loop the program checks for if-condition. If the condition is True, the break statement terminates the while loop, and control passes to the next statement after the loop.

num = 3
while(num != 0):
    if(num == 1):
        break
    print("num is: ", num)
    num -= 1

The output for the above code is given below.

num is:  3
num is:  2

Execution of break statement with a nested loop

Let us consider two nested for loops that iterate from a range of 1 to 3. When the innermost loop starts executing, It checks for the value of in_value. If the value of in_val is 2, the break statement terminates the loop, and then control passes to the outer loop.

for out_val in range(1,3):
    for in_val in range(1,3):
        if in_val == 2:
            break
        print("out_val = ",out_val,",","in_val = ",in_val)
        

The output for the above code is given below.

out_val =  1 , in_val =  1
out_val =  2 , in_val =  1
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions