How to break out of a loop in Python?

Published on Aug. 22, 2023, 12:19 p.m.

To break out of a loop in Python, you can use the break statement. The break statement allows you to exit the loop at any point, even if the loop condition has not been met. Here is a simple example:

for i in range(10):
    if i == 5:
        break
    print(i)

In this example, we’re using a for loop to iterate over the range 0 to 9. Inside the loop, we’re checking if i is equal to 5 using an if statement. If i is equal to 5, we break out of the loop using the break statement. Otherwise, we print the current value of i.

When you run this code, it will output:

0
1
2
3
4

This is because the loop is broken when i is equal to 5, and the code inside the loop is no longer executed.

Note that the break statement only breaks out of the nearest enclosing loop, so if you’re using nested loops, you’ll need to use multiple break statements to break out of each loop individually.

Also, keep in mind that excessive use of the break statement can lead to poorly structured code that is difficult to understand and maintain. It’s generally better to use loops that have a clearly defined exit condition whenever possible.

Tags: