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 .
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
break keyword in Java Language
Continue statements in C language
How to find reverse number using method In this article, we will discuss the concept…
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…
C Program to multiplication table using Array In this tutorial , we will discuss about…