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 statements.
The syntax of break statement
break
How to work break statement in Python for loop
How to work break statement in Python while 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
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
Continue statements in C language
PHP Star Triangle pattern program In this tutorial, we will discuss about PHP Star Triangle…
PHP Full Pyramid pattern program In this tutorial, we will discuss about PHP Full Pyramid…
5 methods to add two numbers in Java In this tutorial, we will discuss the…
Python full Pyramid star pattern program In this tutorial, we will discuss the concept of…
Write a function or method to convert C into F -Entered by the user In…
How to write a function or method to convert Celsius into Fahrenheit In this tutorial,…