Table of Contents
Breaking out of loops with `break`
Sometimes you don’t want a loop to run all the way to the end. You may want to:
- Stop as soon as you find what you’re looking for
- Exit early when a certain condition happens
- Avoid running useless extra iterations
The break statement lets you immediately stop the current loop.
When Python sees break inside a loop:
- It stops the loop right away (even if the loop condition is still
Trueor values are left to iterate over). - It jumps to the first line after the loop.
Basic pattern:
while condition:
# some code
if stop_condition:
break
# more codeor
for item in collection:
# some code
if stop_condition:
break
# more codeExample: stop when a number is found
numbers = [3, 8, 12, 5, 7, 12, 9]
target = 12
for n in numbers:
print("Checking:", n)
if n == target:
print("Found it!")
break
print("Loop finished.")Output:
Checking: 3
Checking: 8
Checking: 12
Found it!
Loop finished.
Even though there are two 12 values in the list, the loop stops after finding the first one.
Using `break` in a `while` loop
You can also use break to stop a while loop that would otherwise keep going.
while True: # infinite loop on purpose
text = input("Type 'exit' to quit: ")
if text == "exit":
print("Goodbye!")
break
print("You typed:", text)
Here, while True creates a loop that could run forever, but break gives us a controlled exit when the user types "exit".
`break` in nested loops
When you use loops inside loops (nested loops), break only stops the innermost loop where it appears.
for i in range(3):
print("Outer loop i =", i)
for j in range(5):
if j == 2:
print(" Inner loop breaking at j =", j)
break
print(" Inner loop j =", j)Output:
Outer loop i = 0
Inner loop j = 0
Inner loop j = 1
Inner loop breaking at j = 2
Outer loop i = 1
Inner loop j = 0
Inner loop j = 1
Inner loop breaking at j = 2
Outer loop i = 2
Inner loop j = 0
Inner loop j = 1
Inner loop breaking at j = 2
The break only exits the for j in range(5) loop. The outer loop over i keeps running.
If you need to stop all loops, you typically:
- Use a
flagvariable - Or
returnfrom inside a function (once you know functions)
Example with a flag:
found = False
for i in range(3):
for j in range(3):
if i == 1 and j == 2:
found = True
break # breaks inner loop only
if found:
break # breaks outer loop
print("Stopped at i =", i, "j =", j)Skipping to the next iteration with `continue`
Sometimes you don’t want to stop the loop, but you want to skip the rest of the current iteration and move on to the next one.
The continue statement does exactly that:
- It skips any remaining code in the loop body for the current item/iteration
- It jumps back to the top of the loop and starts the next iteration (if any)
Basic pattern:
for item in collection:
# some code
if skip_condition:
continue
# this code is skipped when skip_condition is Trueor
while condition:
# some code
if skip_condition:
continue
# more code that might be skippedExample: skip negative numbers
numbers = [3, -2, 5, -7, 10]
for n in numbers:
if n < 0:
# Skip negative numbers
continue
print("Processing:", n)Output:
Processing: 3
Processing: 5
Processing: 10The negative numbers are ignored; the loop continues with the next element.
Using `continue` in a `while` loop
Be careful with continue in while loops: you must still make sure the loop condition can change, or you might create an infinite loop.
n = 0
while n < 5:
n += 1
if n == 3:
# Skip number 3
continue
print("n is", n)Output:
n is 1
n is 2
n is 4
n is 5
Notice we increment n before the continue. If we moved n += 1 to after the continue, the loop might never reach 5.
Combining `continue` with other logic
continue is useful when you want to:
- Skip invalid or unwanted inputs
- Ignore special cases
- Keep your code less deeply indented
Without continue:
for n in range(10):
if n % 2 == 0:
print("Even:", n)
With continue and extra logic:
for n in range(10):
if n % 2 != 0:
# Skip odd numbers
continue
print("Even:", n)
Both versions print even numbers, but the continue approach is sometimes clearer when there are more conditions and more code.
Comparing `break` and `continue`
break and continue both affect how loops run, but in different ways:
break:- Ends the loop completely
- Execution continues after the loop block
continue:- Skips the rest of the current iteration
- Goes back to the top of the loop for the next iteration
Example showing both:
for n in range(1, 10):
if n == 7:
print("Stopping loop at", n)
break # stop completely when n is 7
if n % 2 == 0:
continue # skip even numbers
print("Odd number:", n)Output:
Odd number: 1
Odd number: 3
Odd number: 5
Stopping loop at 7Flow:
- For even numbers, we skip the
print("Odd number:", n)line. - When
nreaches 7, we never reach thecontinue; instead webreakand finish the loop.
Common patterns with `break` and `continue`
1. Searching with early exit (`break`)
names = ["Alice", "Bob", "Charlie", "Diana"]
search = "Charlie"
found = False
for name in names:
if name == search:
found = True
break
if found:
print(search, "was found in the list.")
else:
print(search, "was not found.")
break saves time by stopping as soon as we find the match.
2. Filtering values (`continue`)
values = [0, 10, -5, 3, 0, 8]
for v in values:
if v == 0:
# skip zeros
continue
print("Non-zero value:", v)We only process the non-zero values.
3. Simple menu with exit option (`break`)
while True:
print("Menu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Exit")
choice = input("Choose an option (1-3): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice.")
Here break cleanly exits the loop when the user picks option 3.
When to avoid `break` and `continue`
break and continue are useful, but overusing them can make code harder to follow.
Guidelines:
- It’s fine to use them for clear, simple control flow, like:
- Exiting a menu
- Stopping a search early
- Skipping invalid items
- Avoid sprinkling many
break/continuestatements throughout long loops. If the flow starts to feel confusing, consider: - Splitting logic into functions
- Using clearer conditions in the loop header
- Using variables (flags) to express state
As you practice, you will get a feel for when break and continue make your code easier to read, and when they make it more complicated.