In this post, we’ll learn how to use Python break statement in Python code. We’ll explain everything in detail from its syntax to its proper implementation in practical examples.
After reading this post, you’ll be able to incorporate Python break statement in your own Python code with ease.
So let’s not wait anymore and just dive right into it.
What is Python Break Statement?
It is used to change/stop the flow of Python loops. As we already know, the loop continues to execute until the condition is false. But sometimes, we want to stop the loop before its completely executed. For that, we use Python break statement.
It breaks the loop and the statements after the loop starts executing. If we have a nested loops and the break statement is used in the inner loops then they will get terminated.
Let’s now understand Python break statement with proper practical examples. But first, let’s understand its syntax.
Syntax of Break
break
This is the keyword that you have to use if you want to break the loop at some specific point.
Implementing Python Break Statement (Multiple Examples)
Let’s now understand the working of break statement practically.
Example 1: Integer in For Loop
for i in range(10): print(i) if(i==4): break // breaks the loop print('THE LOOP ENDS') // statement outside loop
Output
0 1 2 3 4 THE LOOP ENDS
You can see that we have specified a condition that if the value of integer is equal to 4 then break the loop. As a result, the loop breaks successfully and the statement outside the loop got executed.
Example 2: String in For Loop
val='Purple' for i in val: print(i) if(i=='l'): break // breaks the loop from here print('THE LOOP ENDS') // outside loop
Output
P u r p l THE LOOP ENDS
As you can see that we have specified a string and have looped over it. We also have used a condition that the value which will take every item of the string while the loop executes is equal to alphabet l(L). Then execute the if statement body in which Python break statement is implemented.
So when the value matches, the break will execute which will break the loop flow and shift the control outside the loop.
So this is how you can easily implement Python break statement in your code. Hope you like this post.
Don’t hesitate to ask if you still have any questions related to the implementation of Python break statement. I’ll be very glad to answer all.
Conclusion
To conclude, hope you now have a clear, in-depth idea of how to properly use Python break statement. I would love to have your thoughts on this post. Thank you for reading it.