How to Use break in Python Loops with Examples

Python Python Basics

In programming, we often need to control the flow of our code based on certain conditions. One such condition is when we want to exit a loop prematurely. This can be achieved using the break statement. In this blog post, I will explain how to use break with both for and while loops in Python.

Table of Contents

Using break with for Loops

The for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). The break statement can be used to exit the for loop prematurely. Here’s an example:


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

In this code, we are iterating over a range of numbers from 0 to 9. When i equals 5, the break statement is executed and the loop is exited prematurely. As a result, only the numbers from 0 to 4 will be printed.

Using break with while Loops

The while loop continues to execute as long as the condition remains true. The break statement can also be used to exit the while loop prematurely. Here’s an example:


i = 0
while True:
    if i == 5:
        break
    print(i)
    i += 1

In this code, we are using an infinite while loop (with the condition set to True). When i equals 5, the break statement is executed and the loop is exited prematurely. As a result, only the numbers from 0 to 4 will be printed.

Conclusion

The break statement in Python allows us to control the flow of our code by breaking out of loops early when certain conditions are met. This can greatly simplify our code and make it more efficient. Whether you’re working with a for loop or a while loop, understanding how to use the break statement is an important part of becoming proficient in Python programming.

To top