break — Easy Examples
Exits the nearest enclosing for or while loop immediately
Exit a loop early
Using break to stop a loop when a condition is met.
python
# Find the first number divisible by 7 for i in range(1, 100): if i % 7 == 0: print(f"First multiple of 7: {i}") break # Break out of a while loop password = ["wrong", "wrong", "correct", "wrong"] attempt = 0 while attempt < len(password): if password[attempt] == "correct": print(f"Access granted on attempt {attempt + 1}") break attempt += 1
Expected Output
First multiple of 7: 7 Access granted on attempt 3
break immediately exits the innermost loop. Code after break in the loop body is skipped.
Break with user-like input
Simulating an input loop with break.
python
commands = ["help", "status", "run", "quit", "more"] for cmd in commands: if cmd == "quit": print("Goodbye!") break print(f"Running: {cmd}")
Expected Output
Running: help Running: status Running: run Goodbye!
break is commonly used to exit loops when a sentinel value or exit condition is found.
Want to try these examples interactively?
Open Easy Playground