Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Loop Control Statements in Python
Loop control statements in Python allow you to change the execution flow of loops. These statements provide flexibility to terminate loops early, skip iterations, or act as placeholders in your code structure.
The break Statement
The break statement terminates the loop immediately and transfers control to the statement following the loop ?
# Using break in a for loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num == 5:
print(f"Found {num}, breaking the loop")
break
print(f"Current number: {num}")
Current number: 1 Current number: 2 Current number: 3 Current number: 4 Found 5, breaking the loop
Using break with while Loop
count = 0
while True:
print(f"Count: {count}")
count += 1
if count >= 3:
print("Breaking infinite loop")
break
Count: 0 Count: 1 Count: 2 Breaking infinite loop
The continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop ?
# Skip even numbers
for i in range(1, 8):
if i % 2 == 0:
continue
print(f"Odd number: {i}")
Odd number: 1 Odd number: 3 Odd number: 5 Odd number: 7
The pass Statement
The pass statement is a null operation that serves as a placeholder when syntax requires a statement but no action is needed ?
# Using pass as a placeholder
for i in range(5):
if i < 3:
pass # TODO: implement logic later
else:
print(f"Processing item: {i}")
Processing item: 3 Processing item: 4
pass in Function Definition
def future_function():
pass # Placeholder for future implementation
# Function exists but does nothing
future_function()
print("Function called successfully")
Function called successfully
Comparison of Loop Control Statements
| Statement | Effect | Use Case |
|---|---|---|
break |
Exits loop completely | Stop when condition is met |
continue |
Skips current iteration | Skip specific values |
pass |
Does nothing | Placeholder for future code |
Nested Loops with Control Statements
# break only affects the innermost loop
for i in range(3):
print(f"Outer loop: {i}")
for j in range(3):
if j == 1:
break
print(f" Inner loop: {j}")
Outer loop: 0 Inner loop: 0 Outer loop: 1 Inner loop: 0 Outer loop: 2 Inner loop: 0
Conclusion
Loop control statements provide essential flow control in Python loops. Use break to exit loops early, continue to skip iterations, and pass as a syntactic placeholder when developing code incrementally.
