Introduction
In this lesson, you will deepen your understanding of loop control in Python using three powerful tools:
break– exit a loop early when a condition is metcontinue– skip the rest of the current iteration and move to the nextelsewith loops – run code only if the loop completed without abreak
You already know how for and while loops work. Now you will learn how to control when and how they stop or skip work, and how to reason about complex flows using these statements together.
Using break to Exit Loops Early
break immediately stops the nearest enclosing loop, regardless of the loop’s condition.
Example: Stop Searching When Found
numbers = [3, 7, 11, 15, 21, 28]
target = 15
for n in numbers:
if n == target:
print("Found target:", n)
break
print("Checked:", n)
# Output
Checked: 3
Checked: 7
Checked: 11
Found target: 15
Explanation:
- The loop checks each number.
- When
n == 15, it prints "Found target" andbreakstops the loop. - Remaining elements (
21,28) are never checked.
Use break when continuing the loop would be unnecessary or inefficient.
Using continue to Skip the Current Iteration
continue stops the current iteration and jumps directly to the next one, without exiting the loop.
Example: Process Only Even Numbers
values = [1, 2, 3, 4, 5, 6]
for v in values:
if v % 2 != 0:
continue # skip odd numbers
print("Even value:", v)
# Output
Even value: 2
Even value: 4
Even value: 6
Explanation:
- When
vis odd,continueruns and theprintis skipped. - When
vis even, theifcondition is false andprintexecutes.
Use continue when some items should be ignored but you still want the loop to run for the rest.
Combining break and continue for Complex Patterns
You can use both in the same loop to express more nuanced logic.
Example: Validate User Inputs with Limits
Imagine you allow the user up to 5 attempts to enter a valid positive integer. Negative numbers are ignored (skipped), and zero cancels the process entirely.
attempts = 0
max_attempts = 5
while attempts < max_attempts:
raw = input("Enter a positive integer (0 to cancel): ")
attempts += 1
if not raw.isdigit():
print("Not a valid number, try again.")
continue # don't process further, go to next attempt
value = int(raw)
if value == 0:
print("Cancelled by user.")
break # exit the loop completely
if value < 0:
# This case won't happen with isdigit(), but kept for illustration
print("Negative values are ignored.")
continue
print("You entered:", value)
print("Done.")
# Example Output (one possible run)
Enter a positive integer (0 to cancel): hello
Not a valid number, try again.
Enter a positive integer (0 to cancel): 42
You entered: 42
Enter a positive integer (0 to cancel): 0
Cancelled by user.
Done.
Explanation:
continueis used to skip invalid inputs but keep the loop running.breakis used to stop everything when the user enters0.- This pattern is common in input validation, menu systems, and interactive programs.
Using else with Loops
Python allows an else block after a for or while loop. The else suite runs only if the loop ends normally, without hitting a break.
Example: Search with for-else
numbers = [4, 6, 9, 13]
target = 10
for n in numbers:
if n == target:
print("Found:", n)
break
else:
print("Target not found in list.")
# Output
Target not found in list.
Explanation:
- The loop checks all numbers; none are equal to
10. - Since no
breakoccurred, theelseblock runs and prints the message. - If
targetwere13, thebreakwould fire and theelsewould be skipped.
This is ideal for search tasks where you need to distinguish between:
- "I found it and stopped early" vs.
- "I finished the loop and never found it".
while-else with Early Termination
The same concept applies to while loops.
Example: Counting Down with a Condition
count = 5
while count > 0:
print("Count:", count)
if count == 2:
print("Condition met, stopping early.")
break
count -= 1
else:
print("Countdown finished without early stop.")
# Output
Count: 5
Count: 4
Count: 3
Count: 2
Condition met, stopping early.
Explanation:
- The loop would normally run until
countbecomes0. - But when
counthits2,breakstops the loop. - Because of
break, theelsesuite does not execute.
If you removed the if/break block, the loop would finish naturally and the else would run.
Debugging and Predicting Loop Flow
When break, continue, and else interact, tracing the flow is critical. A useful strategy is to add temporary debug prints.
Example: Tracing a Loop with All Three
items = ["ok", "skip", "ok", "stop", "ok"]
for item in items:
print("Start iteration with:", item)
if item == "skip":
print(" -> continue (skip processing)")
continue
if item == "stop":
print(" -> break (exit loop)")
break
print(" -> processing", item)
else:
print("Loop completed without 'stop'.")
# Output
Start iteration with: ok
-> processing ok
Start iteration with: skip
-> continue (skip processing)
Start iteration with: ok
-> processing ok
Start iteration with: stop
-> break (exit loop)
Explanation:
"skip"triggerscontinue, so the "processing" line is skipped for that iteration."stop"triggersbreak, so any remaining items are not processed.- Because a
breakhappened, theelseblock is not executed. - The debug prints show exactly which branch runs in each iteration.
When debugging your own loops:
- Add prints before and after
ifconditions. - Mark lines like
"-> break","-> continue", and"-> normal end". - Once the logic is clear and correct, remove or comment out those debug messages.
Summary / Key Takeaways
In this lesson on break, continue, and else with loops, you learned:
breakexits loops early when a specific condition is met, preventing further iterations.continueskips the rest of the current iteration and moves directly to the next loop cycle.breakandcontinuecan be combined in the same loop to express complex control flows like input validation and menu handling.- Loop
elseblocks execute only when nobreakoccurs, letting you distinguish between "found" and "not found" in search patterns. for-elseis ideal for search operations, signaling when a loop finishes without finding a target.while-elseworks the same way, running theelseonly if the loop condition becomes false without abreak.- Debug prints help trace loop behavior, making it easier to understand and fix interactions between
break,continue, andelse. - Thinking in terms of loop exit paths (normal completion vs. early termination) improves your ability to design predictable iteration patterns.
