⬅ Previous Topic
Python While LoopNext Topic ⮕
Introduction to Python Collections⬅ Previous Topic
Python While LoopNext Topic ⮕
Introduction to Python CollectionsIn 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.
break
in PythonThe 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.
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
As soon as the number reaches 3, the break
statement is executed. The loop exits, so we never see 4 or 5 printed.
continue
in PythonThe 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.
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
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.
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 |
If you use break
or continue
in a while
loop, be extra careful:
break
, ensure that the condition to exit is reachable.continue
, make sure the loop variables are still being updated, or you risk an infinite loop.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
break
for early exit when a target is found—such as stopping after finding a match in a search.continue
when you want to filter out certain conditions but still want the loop to proceed.break
and continue
manage clarity inside the loop.break
and continue
are vital tools in Python loop control. Whether you're searching through data, filtering results, or just making sure your logic flows cleanly, these statements help you stay precise and expressive. Practice writing small loop variations to master them.
⬅ Previous Topic
Python While LoopNext Topic ⮕
Introduction to Python CollectionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.