Python break Statement Explained

The break statement in Python is used to exit a loop prematurely. When a break statement is encountered, the loop is terminated, and the program control jumps to the next statement after the loop.

Syntax

for variable in iterable:
    # loop body
    if condition:
        break
# next statement after the loop

or

while condition:
    # loop body
    if another_condition:
        break
# next statement after the loop

Breaking Out of a For Loop

numbers = [1, 3, 5, 12, 15, 20]
for number in numbers:
    if number > 10:
        print("Found a number greater than 10:", number)
        break
else:
print("No number greater than 10 found.")

Breaking Out of a While Loop

Suppose you want to ask a user for input until they enter a valid number:

while True:
    user_input = input("Enter a number: ")
    if user_input.isdigit():
        number = int(user_input)
        print("You entered:", number)
        break
    else:
        print("Invalid input. Please enter a number.")

Breaking with Nested Loops

Example:

for i in range(3):
    for j in range(3):
        if i == j:
            break
        print(i, j)

Output:

1 0
2 0
2 1