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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap