Loop control statements modify the normal flow of a loop. Python provides three keywords for this purpose: break
, continue
, and pass
.
break
- Purpose: Terminates the loop entirely.
- Usage: Often used when a specific condition is met and further iterations are unnecessary.
Python
numbers = [2, 3, 5, 7, 11, 13]
for num in numbers:
if num > 6:
break
print(num)
continue
- Purpose: Skips the current iteration of the loop and moves to the next iteration.
- Usage: Useful for skipping specific elements or conditions within a loop.
Python
numbers = [2, 3, 5, 7, 11, 13]
for num in numbers:
if num % 2 == 0:
continue
print(num)
pass
- Purpose: Does nothing. Often used as a placeholder when a statement is syntactically required but no action is needed.
- Usage: Common in empty function or class bodies.
Python
def function():
pass # Placeholder for future implementation
Key points:
break
andcontinue
can be used in bothfor
andwhile
loops.pass
is generally used as a placeholder and has no effect on the loop’s execution.- Overuse of
break
andcontinue
can make code less readable. Use them judiciously.
When should I use break
?
Use break
to terminate the loop entirely.
When should I use continue
?
Use continue
to skip the current iteration and move to the next.
Can I use break
and continue
in nested loops?
Yes, you can use them in both inner and outer loops.
What is the pass
statement used for?
The pass
statement is a null operation, often used as a placeholder.
Can I use multiple break
or continue
statements in a loop?
Yes, you can use multiple break
or continue
statements within a loop.
How do break
and continue
affect loop performance?
Frequent use of break
or continue
might impact loop performance.