Robotics & Artificial Intelligence

Explain the use of break statement in Python with the help of an example.

Python Control Flow

1 Like

Answer

The break statement in Python is used to terminate a loop immediately and transfer the control outside the loop, even if the loop condition is still true.

Example:

numbers = [1, 2, 3, 4, 5]

for n in numbers:
    if n == 4:
        break
    print(n)
print("The end")

Output:

1
2
3
The end

In this example, the loop iterates through the list numbers. When the value 4 is encountered, the break statement is executed, which stops the loop immediately and the control comes out of the loop. After the loop ends, the statement print("The end") is executed.

Answered By

2 Likes


Related Questions