How Can We Help?
This tutorial will explain how to break a loop in Python. We will see how to put the break in different positions by giving practical examples for better understanding.
What is Break Statement in Python?
The break statement is a stop statement. It is used to pass the control to the end of the loop. When putting a break statement in the body of a loop, the loop stops executing, and control shifts automatically to the first statement after the loop. It can be used in while loop as well as for loop statements.
Python Break Loop Syntax
loop_expression:
body of loop
break
Basic Break Statment Example:
for i in 'break':
if i=='a':
print("Element found")
break
print(i)
Output
B
r
e
Element found
Explanation:
The above example shows the break statement inside the if statement. It says to stop the ‘if’ function when i=a, so for loop runs three times only as i=(b,r,e) and returns the output as ‘ b r e’ against the execution of print statement as “print(i)”. when i=a in loop, it returns output as ‘Element found’ against execution of print statement as “print(“Element found”)”.
We can apply break statements in python in two ways.
Loop with Break Condition in the Middle
This kind of loop can be implemented using an infinite loop and a conditional break between the loop’s body.
Example:
Write a program to test entered character is a vowel or not by using the break statement.
vowels='aeiouAEIOU'
while True:
v=input("Enter a vowel: ")
if v in vowels:
break
print(v,'is not a vowel')
print('You pass the test')
Output:
Enter a vowel: 5
5 is not a vowel
Enter a vowel: 6
6 is not a vowel
Enter a vowel: a
You pass the test
Loop with Break Condition at the Bottom
This kind of loop ensures that the loop’s body is executed at least once. It can be implemented using an infinite loop and a conditional break at the end. This is similar to the do…while loop in C. The do..while loop tests the condition after executing the statements within the loop.
Example:
Write a program to roll the dice in a dice game by using the break statement.
import random
while True:
input("Press enter to roll the dice ")
num=random.randint(1,6)
print("you got", num)
option=input("roll again? (y/n)")
if option == 'n':
break
Output:
Press enter to roll the dice
you got 3
roll again? (y/n)y
Press enter to roll the dice
you got 4
roll again? (y/n)
Conclusion
In this tutorial, We have learned how to use loop break statement in Python, you also learned how to use put break statement in different positions like (middle and bottom).
Hopefully, it was clear and concise.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.
Related Articles
Python Loop Statements – Comprehensive Guide
Python Tutorials List:
- Python tutorials list : access all python tutorials.