How to break out of a loop in Python?

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

To break out of a loop in Python, you can use the break keyword. When the break keyword is encountered within a loop, it immediately exits the loop and continues execution of the code following the loop.

Here’s an example:

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

In this example, the loop will iterate through the numbers 0 to 9. When i equals 5, the break keyword is encountered and the loop immediately exits. The output of the above code will be:

0
1
2
3
4

Note that break can be used with both for and while loops in Python. Additionally, you can use the break keyword with nested loops to break out of both the current loop and any outer loops.

Tags: