What is the purpose of the break statement in Python?

What is the purpose of the break statement in Python?

a) To skip the current iteration of a loop
b) To terminate the loop entirely
c) To restart the loop
d) To exit the program

Answer:

b) To terminate the loop entirely

Explanation:

The break statement in Python is used to terminate a loop prematurely. When the break statement is encountered, the loop is immediately exited, and the program continues with the next statement following the loop.

for i in range(10):
    if i == 5:
        break  # Exits the loop when i equals 5
    print(i)  # Prints 0, 1, 2, 3, 4

The break statement is particularly useful when you want to stop the loop based on a specific condition, such as finding a matching item in a list or detecting an error condition that requires exiting the loop.

By using the break statement, you can make your loops more dynamic and responsive, allowing them to terminate early when certain criteria are met.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top