Exit the loop with break #
In Python, the break statement is used to prematurely exit a loop. When encountered within a loop, the break statement immediately terminates the loop and transfers the program execution to the next statement after the loop.
Here's an example of using break to stop a for loop:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
for fruit in fruits:
if fruit == "cherry":
break
print(fruit)
print("Loop finished")
In this example, the loop iterates over the fruits list. When the fruit variable becomes equal to "cherry", the break statement is encountered, and the loop is exited. As a result, only "apple" and "banana" will be printed, and the program execution will continue with the statement after the loop, which is print("Loop finished").
The output of the above code will be:
apple
banana
Loop finished
Using with while loops #
We can use break statements with while loops as well. In the example below, we use the break statement to stop the execution of the while loop when x equals 3.
x = 0
while True:
print(f"The number is {x}")
if x == 3:
break
x = x + 1
print("This is called after the loop")
Output
The number is 0
The number is 1
The number is 2
The number is 3
This is called after the loop
Exercise #
- Use
breakto stop the loop when the valuenumberis equal to5, so that the functionprint()is called 5 times.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules