Intern
How can you interrupt the execution of a loop in Python?
sobes.tech AI
Answer from AI
To interrupt the execution of a loop, the break and return statements are used, as well as exception handling.
break terminates the nearest enclosing loop (for, while) and transfers control to the statement following the loop.
# Example of using break
for i in range(10):
if i == 5:
break # Interrupts the loop at i = 5
print(i)
return terminates the execution of a function or method and returns a value. If the loop is inside a function, return will interrupt both the loop and the function execution.
# Example of using return in a function with a loop
def find_item(items, needle):
for item in items:
if item == needle:
return item # Interrupts the loop and the function, returning the found item
return None # If the item is not found after the loop
result = find_item([1, 2, 3, 4, 5], 3)
print(result)
Exceptions can be used to interrupt loop execution, especially if the break condition arises due to an error or special state.
# Example of interrupting a loop with an exception
class CustomInterrupt(Exception):
pass
try:
for i in range(10):
if i == 7:
raise CustomInterrupt("Interrupt on condition")
print(i)
except CustomInterrupt as e:
print(f"Loop interrupted: {e}")
Summary table of methods:
| Method | Scope of action | Purpose |
|---|---|---|
break |
Nearest enclosing loop | Interrupts the loop |
return |
Function/method (including nested loops) | Interrupts the function/method and returns |
| Exception | Current try/except block or higher |
Error handling or special conditions |