Codeforcoding

Break statement in python programming language

Break statement in python programming language

We will learn about how break statement work in python programming language. Break statement alter the flow of control of normal loops(for loop and while loop) and it is used to terminate the flow of the loop.

break statement performs based on the boolean expression.
Typically, loops iterate over the block of statements until test expression is false. but, if we want we can terminate the current iteration before the loops can complete their iteration using the break .

Python programming break statements

Declaration

The syntax of break statement

break

Flow diagram for break  in Python

Break statement in python programming language
flow diagram -break in Python

How to work break statement in Python for loop

break statement in Python for loop

How to work break statement in Python while loop

break statement in Python while loop

Example for the  break in for loop

program 1

 

for val in range(1,10):
    if val==5:
        break
    print val
print('End of the loop')

 

When the above code is compiled and executed, it will produce the following results

1
2
3
4
End of the loop

 

In the program when becoming vall==5 break statement executed and exit of the loop

program 2

n=input("Enter any number for n :")
sum=0 #initialized sum as zero

for i in range(1,10):
    if i==n:
        break #teminated loop using break

    sum=sum+i
    print sum
print("End of loop")

 

When the above code is compiled and executed, it will produce the following results

Output 1

Enter any number for n: 4
1
3
6
End of loop

 

Output 2

Enter any number for n: 6
1
3
6
10
15
End of loop

 

Example for the break in while loop

Program 1

i=1
while i<=10:
    if i==5:
        break
    print i
    i=i+1
print("End of loop")

 

At above program, when becoming i==5 break statement executed and control flow exit from the loop

When the above code is compiled and executed, it will produce the following results

1
2
3
4
End of loop

 

Program 2

n=input("Enter any number for n :")
sum=0 #initialized sum as zero
i=1
while i<=10:
    if i==n:
        break #terminated loop using break
    sum=sum+i
    print sum
    i=i+1
print("End of loop")

 

When the above code is compiled and executed, it will produce the following results

Output 1

Enter any number for n: 4
1
3
6
End of loop

Output 2

Enter any number for n: 6
1
3
6
10
15
End of loop

Output 3

Enter any number for n: 9
1
3
6
10
15
21
28
36
End of loop

 

Suggested for you

break keyword in  Java Language

Keyword in Python language

Continue statements in Python

Continue statements in C language

Keyword in C language

Keyword in Java language

for loop in C language

While loop in C language

for loop in Python

While loop in Python

 

Exit mobile version