The Python break Statement is an important one used to alter the flow of a program. We would like to share two examples to display the working functionality of the Python Break statement in both For loop and While loop
Loops are used to execute certain block of code for n number of times until the test condition is false. There will be some situations where, we have terminate the loop without executing all the statements. In these situations we can use Python break statement.
Python break Statement
The Python break statement is very useful to exit from For Loop, While and Nested Loops. While executing these code blocks, if the compiler finds the break inside them, the compiler will stop executing the statements inside it and exit immediately from the iteration.
For example, we have 5 lines of code inside the loop and we want to exit from it when certain condition is True otherwise, it has to execute them. In these situations we can place the Python Break statement inside the If condition.
If the condition is True then compiler will execute the break statement. It means, the this will exit the controller from the loop completely. Otherwise, it will execute all block of code.
Python Break Syntax
The syntax of the Python break Statement is as follows:
Python break Statement in For and While loop
In this program, We are going to use the Python break statement in For Loop to exit from the block iteration.
In this Python break statement in for loop example, First, we used the for loop with range() and we are not going to explain the iteration wise execution here.
Inside the for loop we placed If condition to test whether I is equal to 6. If the condition is false then it will skip this and prints that number as output (In Our case 0, 1, 2, 3, 4, 5) using the print function.
If this condition ( i == 6) is True then Break statement will execute and the iteration will stop at that number without printing the following print function:
for i in range(0, 11): if i == 6: break print("The Value of the Variable i is: ", i)
In this program, We are going to use the Python break statement inside the While loop to exit from the iteration.
In this Python break while loop example, We initialized the value of i as: i = 0 at the beginning of the code. Within this, we check for the condition whether i is less than or equal to 10 or not.
Inside the While loop we placed Python If condition to test whether I is equal to 4. If the condition is false, it will skip this case. Next, it prints that number as output (In Our case 0, 1, 2, 3) using the following print function.
If this condition (i == 4) is True then Break executes and the iteration will stop at that number without printing the following print function.
i = 0 while i <= 10: print(" The Value of the Variable i = ", i) i = i + 1 if i == 4: break
The Value of the Variable i = 0
The Value of the Variable i = 1
The Value of the Variable i = 2
The Value of the Variable i = 3