Blog Post #38: Taking Control: How to Exit a Loop Early with break

So far, the loops we’ve written have all had one thing in common: they run until their natural end. A for loop runs for every item in a sequence, and a while loop runs until its condition becomes false. But what if you need to stop a loop prematurely?

Imagine you are searching through a list of a million items for a specific one. If you find it on the 10th try, it would be a huge waste of time to continue checking the other 999,990 items.

To solve this, Python gives us the break statement. In this post, we’ll learn how to use break to exit a loop on command, based on a condition inside the loop.

What is the break Statement?

The break statement immediately terminates the current loop. As soon as Python executes the break keyword, it jumps out of the loop entirely and continues execution at the very next statement after the loop’s indented block.

It’s an “emergency exit” that you can trigger from inside the loop’s body, usually from within an if statement.

Using break in a for Loop

The most common use case for break in a for loop is to stop a search once the desired item has been found. This makes your code much more efficient.

Let’s write a program that searches for a specific number in a list.

numbers = [1, 5, 12, 44, 98, 43, 22, 67]
number_to_find = 43

for number in numbers:
    print(f"Checking {number}...")
    if number == number_to_find:
        print(f"Found it! The number is {number_to_find}.")
        break # Exit the loop immediately

print("Search finished.")

When you run this code, the output will be:

Checking 1...
Checking 5...
Checking 12...
Checking 44...
Checking 98...
Checking 43...
Found it! The number is 43.
Search finished.

Notice that the loop stopped immediately after finding 43. The numbers 22 and 67 were never checked because the break statement was executed, saving unnecessary work.

Using break in a while Loop

The break statement is also extremely useful in while loops. A common and very readable pattern is to create what looks like an infinite loop with while True:, and then use an if statement inside to check for an exit condition.

This is an alternative to the boolean flag method we used in our menu project in Post #33.

# This loop will run forever until a 'break' is hit
while True:
    user_input = input("Enter a command (or type 'quit' to exit): ")
    
    if user_input == "quit":
        print("Exiting the program...")
        break # The only way to exit this loop
    
    print(f"You typed: {user_input}")

print("Goodbye!")

Here, the while True: statement creates a loop that would otherwise run forever. The if statement inside provides the only escape hatch. When the user types “quit,” the break is executed, and the program continues to the final “Goodbye!” message.

What’s Next?

The break statement gives you precise control over your loops, allowing you to stop them the moment your goal is achieved instead of waiting for the loop to finish its natural course. It is an essential tool for writing efficient and responsive code.

break allows us to exit a loop entirely. But what if we don’t want to exit the whole loop, but just want to skip the rest of the code in the current iteration and jump straight to the next one? For this, Python provides a sibling to break. In Post #39, we will learn how to use the continue statement.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment