Python Break Statement

The break statement is a control flow statement in Python used to exit a loop prematurely. It is typically used within for and while loops to terminate the loop's execution when a certain condition is met. When the break statement is encountered, the loop in which it resides is immediately exited, and the program continues with the next statement after the loop.

        
while condition:
    # some code
    if some_condition:
        break  # Exit the loop if some_condition is True
    # more code
# code after the loop
        
    

And here's an example to illustrate how the break statement works:

        
# Using break in a while loop to find the first even number in a list
numbers = [1, 3, 5, 2, 7, 6, 9]

for num in numbers:
    if num % 2 == 0:
        print(f"Found the first even number: {num}")
        break

print("Loop finished.")
        
    

In this example, we have a list of numbers, and we use a for loop to iterate through them. Inside the loop, we check if the current number is even (i.e., divisible by 2). If we find an even number, the break statement is executed, and the loop is terminated prematurely. The program then proceeds to print "Loop finished." Since the break statement was used, the loop stops as soon as the first even number is found.

Output:

Found the first even number: 2
Loop finished.

As shown in the example, the break statement is a powerful tool for controlling the flow of your loops and exiting them when specific conditions are met. It's essential for creating efficient and responsive code in situations where you don't need to process the entire loop.