Break Statement in Python

The break statement in Python is a control flow tool used to exit a loop before it has completed all of its iterations. It’s often used within for and while loops when a specific condition is met, allowing you to halt the loop early.

Key Points on Break Statement:

Example of Using Break in a Loop:

In this example, a for loop iterates over a list of numbers, and when it encounters the number 5, it breaks out of the loop.

Code Example

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        for num in numbers:
            if num == 5:
                break
            print(num)

Output

1
2
3
4

Break in Nested Loops:

This example demonstrates the use of break within a nested loop structure. Here, the inner loop breaks when it finds an even number.

Code Example 2

for i in range(1, 4):
            for j in range(1, 6):
                if j % 2 == 0:
                    break
                print(f"i={i}, j={j}")

Output

i=1, j=1
i=2, j=1
i=3, j=1

Detailed Explanation:

The break statement is a versatile tool in Python that aids in creating cleaner, more efficient loops by allowing early termination when certain conditions are met.