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.
And here's an example to illustrate how the break
statement works:
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.