How can you exit a loop prematurely in Python?
a) break
b) continue
c) exit
d) stop
Answer:
a) break
Explanation:
In Python, the break
statement is used to exit a loop prematurely. When the break
statement is encountered inside a loop, the loop terminates immediately, and the program continues with the next statement after the loop.
for i in range(10):
if i == 5:
break # Exits the loop when i equals 5
print(i) # Prints 0 to 4
The break
statement is useful when you need to stop the loop based on a condition, such as finding a specific item in a list or handling an error condition.
Using break
provides greater control over loop execution, allowing you to create more dynamic and responsive programs.