break — Intermediate Examples
Exits the nearest enclosing for or while loop immediately
Break with for/else
Using else to detect if break was triggered.
python
# Search with else def find_prime_factor(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return i return n # n is prime # for/else: else runs only if loop completes without break numbers = [15, 7, 20, 11] for n in numbers: for i in range(2, n): if n % i == 0: print(f"{n} is composite (divisible by {i})") break else: print(f"{n} is prime")
Expected Output
15 is composite (divisible by 3) 7 is prime 20 is composite (divisible by 2) 11 is prime
The else clause of a for loop runs only when the loop finishes without hitting break. This is a clean search pattern.
Break in nested loops
Break only exits the innermost loop.
python
# Break only exits ONE level matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] target = 5 found = False for i, row in enumerate(matrix): for j, val in enumerate(row): if val == target: print(f"Found {target} at ({i}, {j})") found = True break if found: break # Cleaner: use a function to break all levels def find_in_matrix(matrix, target): for i, row in enumerate(matrix): for j, val in enumerate(row): if val == target: return (i, j) return None print(find_in_matrix(matrix, 8))
Expected Output
Found 5 at (1, 1) (2, 1)
break only exits the innermost loop. For nested loops, use a flag variable or wrap the search in a function and use return instead.
Want to try these examples interactively?
Open Intermediate Playground