How to Exit a Loop in Python Code

If you have a for loop in your Python code, and you want to exit it on a specific condition, then you can make use of the break statement.

This is just like other programming languages like C, C++, C# or Java.

Example:
check_prime_numbers = [1, 2, 5, 6, 8, 9, 11, 12, 17]

for num in check_prime_numbers:
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            print(f"{num} is not a prime number")
            break
    else:
        print(f"{num} is a prime number")

The above prime number example is a perfect one to understand how to make use of the break statement. We have a list of numbers and we want to know if they are prime or not. As soon as in the nested for loop we understand that the number is not prime we break the loop.

Python how to break a loop example

To know more, do take a look at the official documentation: https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!