In this tutorial, we are going to learn Python Break Statement
The break command in Python is used to end or escape a loop early. It is mainly utilised with loops like for and while to abruptly break the loop’s regular flow.
When the break
statement is encountered within a loop, the program jumps out of the loop and continues execution with the next statement after the loop. This allows you to skip the remaining iterations of the loop and proceed with the rest of the code.
Here’s the general syntax of the break
statement:
while condition:
# Some code here
if condition:
break
# More code here
OR
for item in iterable:
# Some code here
if condition:
break
# More code here
In the above examples, the break
statement is used inside a loop. If the specified condition evaluates to True
, the break
statement is executed, and the loop is immediately terminated. The program then continues execution with the next statement after the loop.
Here’s an example to illustrate the usage of the break
statement:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
print("Loop finished")
Output:
1
2
Loop finished
In the above code, the break
statement is encountered when num
is equal to 3. As a result, the loop is terminated, and the program moves to the next statement after the loop, which is print("Loop finished")
.
Note that the break
statement only terminates the innermost loop in nested loops. If you have multiple nested loops, you can use additional control flags or techniques to break out of outer loops if needed.
Remember, the break
statement is a useful tool for controlling the flow of your loops and providing flexibility in your program logic.