The break statement is a loop control keyword in Python that terminates the execution of the surrounding for or while loop immediately. The moment Python encounters break, it halts further iterations and jumps control directly to the first line of code outside the loop block.
Figure 24.1: Break statement immediately breaking out of the loop and skipping any loop-else blocks.
# Searching for a specific character:
for char in "veewom":
if char == "w":
print(f"Character '{char}' encountered! Breaking loop.")
break
print("Inspecting character:", char)
print("Loop finished execution.")
Inspecting character: v
Inspecting character: e
Inspecting character: e
Character 'w' encountered! Breaking loop.
Loop finished execution.
# Break on sentinel exit command
while True:
command = input("Enter command (or type 'quit' to exit): ").strip()
if command.lower() == "quit":
print("Closing application...")
break
print(f"Executing command: {command}")
break outside a for or while loop causes a SyntaxError: 'break' outside loop.