In Python, break and continue are control statements that alter the natural flow of loops. They help you exit a loop early or skip an iteration based on a condition. These simple yet powerful tools are essential for clean and efficient loop control.
Using break in Python
The break statement is used to exit a loop prematurely when a specific condition is met. Once triggered, it immediately stops the loop and continues with the next line after the loop.
Example: Stop loop when number equals 3
for num in range(1, 6):
if num == 3:
print("Breaking the loop at", num)
break
print("Current number is", num)
Current number is 1
Current number is 2
Breaking the loop at 3
Explanation:
As soon as the number reaches 3, the break statement is executed. The loop exits, so we never see 4 or 5 printed.
Using continue in Python
The continue statement skips the current loop iteration and jumps directly to the next iteration. It’s useful when you want to ignore certain cases but continue looping.
Example: Skip number 3 but continue
for num in range(1, 6):
if num == 3:
print("Skipping", num)
continue
print("Current number is", num)
Current number is 1
Current number is 2
Skipping 3
Current number is 4
Current number is 5
Explanation:
Here, 3 is skipped, but the loop continues to process the remaining numbers. The continue prevents the print below it from executing for number 3.
Break vs Continue: What’s the Difference?
Aspect
break
continue
Effect on Loop
Terminates the entire loop
Skips the current iteration
Next Step
Control goes to the first line after the loop
Control goes back to the loop condition check
Usage
To stop processing early
To avoid processing certain conditions
Real-World Check: Avoiding Infinite Loops
If you use break or continue in a while loop, be extra careful:
With break, ensure that the condition to exit is reachable.
With continue, make sure the loop variables are still being updated, or you risk an infinite loop.
Example: While loop with break
count = 1
while True:
print("Count is", count)
if count == 5:
break
count += 1
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Best Practices
Use break for early exit when a target is found—such as stopping after finding a match in a search.
Use continue when you want to filter out certain conditions but still want the loop to proceed.
Avoid overly complex loop conditions—let break and continue manage clarity inside the loop.
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.