This tutorial will teach you how to use the Python break statement to exit a loop prematurely.
You may want to end a for loop or a while loop early regardless of the results of the conditional tests. In these cases, the break statement can be useful:
break
To end a loop when a condition is True, you typically use the break statement in conjunction with the if statement.
break statement and for loop in Python
The following code demonstrates how to use the break statement within a for loop:
for index in range(n): # more code here if condition: break
The break statement terminates the loop instantly if the condition evaluates to True in this syntax. The remaining iterations will not be completed.
In this example, the break statement is used within a for loop:
for index in range(0, 10): print(index) if index == 3: break
Output
0 1 2 3
How does it work?
The for loop iterates through ten numbers ranging from 0 to 9 and shows each one on the screen.
When the loop number is 3, however, the break statement ends the loop instantly. As a result, the application only displays 4 digits on the screen, ranging from 0 to 3.
In a nested loop, the break statement terminates the innermost loop. As an example:
for x in range(5): for y in range(5): # terminate the innermost loop if y > 1: break # show coordinates on the screen print(f"({x},{y})")
Output
(0,0) (0,1) (1,0) (1,1) (2,0) (2,1) (3,0) (3,1) (4,0) (4,1)
Two for loops are used in this example to display the coordinates from (0,0) to (5,5) on the screen.
When y is bigger than one, the break statement in the nested loop terminates the innermost loop.
As a result, you can only observe coordinates with y values of zero and one.
break statement with while loop in Python
The following example demonstrates how to utilise the break statement within a while loop:
while condition: # more code if condition: break
The break statement is used inside a while loop in the following example.
It will ask you to choose your preferred colour. When you type quit:, the software will terminate.
print('-- Help: type quit to exit --') while True: color = input('Enter your favorite color:') if color.lower() == 'quit': break
Output
-- Help: type quit to exit -- Enter your favorite color:red Enter your favorite color:green Enter your favorite color:blue Enter your favorite color:quit
How does it work?
While True produces an endless loop.
When you type quit, the predicate color.lower() ==’quit’ evaluates to True, and the break statement is executed to end the loop.
Color.lower() returns the colour in lowercase, allowing you to exit the application by typing Quit, QUIT, or quit.
Leave a Reply