Explore Python loop control statements—break, continue. Learn how to manage loop flow for more efficient and readable code.
These statements modify the behavior of loops.
break: Terminates the loop entirely. continue: Skips the current iteration and moves to the next one. pass: Does nothing, often used as a placeholder.
break
StatementExits the loop prematurely.
for item in sequence:
if some_condition:
break # exit the loop
for x in range(3):
if x == 1:
break
print(x)
# Search for the number 5 and exit the loop when found
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
print(f"Checking {num}...")
if num == 5:
print("Number 5 found! Exiting the loop.")
break # Exit the loop
Output:
Checking 1...
Checking 2...
Checking 3...
Checking 4...
Checking 5...
Number 5 found! Exiting the loop.
while
loop# Keep asking for a password until the correct one is entered
correct_password = "python123"
while True:
user_input = input("Enter the password: ")
if user_input == correct_password:
print("Access granted!")
break # Exit the loop
else:
print("Wrong password. Try again!")
Stop monitoring if temperature exceeds a safe limit.
temperatures = [25, 30, 32, 28, 45, 29, 33] # Sensor readings
for temp in temperatures:
if temp > 40:
print(f"ALERT: Temperature {temp}°C is unsafe! Shutting down.")
break # Exit immediately
print(f"Temperature {temp}°C is safe.")
Output:
Temperature 25°C is safe.
Temperature 30°C is safe.
Temperature 32°C is safe.
Temperature 28°C is safe.
ALERT: Temperature 45°C is unsafe! Shutting down.
Use Case:
max_attempts = 3
correct_password = "secret123"
for attempt in range(1, max_attempts + 1):
password = input(f"Attempt {attempt}: Enter password: ")
if password != correct_password:
print("Wrong password. Try again.")
continue # Skip to next attempt
else:
print("Login successful!")
break # Exit loop on success
else:
print("Account locked. Too many failed attempts.")
Output (if user fails 3 times):
Attempt 1: Enter password: hello
Wrong password. Try again.
Attempt 2: Enter password: test
Wrong password. Try again.
Attempt 3: Enter password: 123
Wrong password. Try again.
Account locked. Too many failed attempts.
continue
StatementSkips the current iteration and proceeds to the next iteration of the loop.
for item in sequence:
if some_condition:
continue # skip the rest of the code in this iteration
# code to execute if some_condition is False
continue
StatementSkips the current iteration and moves to the next loop cycle.
# Print only odd numbers (skip even numbers)
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num)
Output:
1
3
5
7
9
continue
StatementSkip invalid entries when processing a dataset.
user_ages = [20, 15, "unknown", 30, -5, 25] # Some invalid data
print("Valid ages:")
for age in user_ages:
if not isinstance(age, int) or age < 0 or age > 120:
continue # Skip invalid entries
print(f"- {age} years old")
Output:
Valid ages:
- 20 years old
- 15 years old
- 30 years old
- 25 years old
pass
StatementA null statement, used as a placeholder.
if condition:
pass # do nothing
The pass
statement is often used in loops as a placeholder or to intentionally skip certain conditions without any action. Here are practical examples demonstrating pass
in different loop scenarios.
pass
in a for
LoopUse Case: Skip specific items without any action.
fruits = ["apple", "banana", "cherry", "kiwi"]
for fruit in fruits:
if fruit == "banana":
pass # Do nothing for banana
else:
print(fruit)
Output:
apple
cherry
kiwi
Explanation:
"banana"
.pass
does nothing and moves to the next iteration.pass
vs continue
in a LoopKey Difference:
pass
→ Does nothing, continues execution.continue
→ Skips the rest of the loop body and moves to the next iteration.pass
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
pass # Just a placeholder, no action
print(num) # This line still runs
Output:
1
2
3
4
5
continue
for num in numbers:
if num == 3:
continue # Skips printing for 3
print(num)
Output:
1
2
4
5
pass
in a while
Loop (Placeholder Logic)Use Case: Temporarily ignore a condition while developing.
count = 0
while count < 5:
if count == 2:
pass # Will handle this case later
else:
print(f"Count: {count}")
count += 1
Output:
Count: 0
Count: 1
Count: 3
Count: 4
Explanation:
count == 2
, pass
does nothing, but the loop continues.pass
in Nested LoopsUse Case: Skip certain combinations in a nested loop.
for i in range(3):
for j in range(3):
if i == j:
pass # Skip when i and j are equal
else:
print(f"i={i}, j={j}")
Output:
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=2
i=2, j=0
i=2, j=1
Explanation:
i == j
, pass
ignores the case.pass
?✅ Placeholder for future code
✅ Intentionally doing nothing in a condition
✅ Silently ignoring exceptions
🚫 Don’t use when:
continue
).break
).break
StatementSimulate a coffee machine that stops serving when a drink is out of stock.
["latte", "cappuccino", "espresso", "mocha", "out_of_stock", "latte"]
Serving latte...
Serving cappuccino...
Serving espresso...
Serving mocha...
Out of stock! Machine stopping.
Calculate the sum of positive numbers in a list, ignoring negatives.
[5, -2, 10, -8, 3]
continue
to skip negative values.Sum of positive numbers: 18
continue
and break
Create a loop that:
continue
).break
).Enter a number (or 'quit'): 5
Enter a number (or 'quit'): ten
Invalid input!
Enter a number (or 'quit'): 3
Enter a number (or 'quit'): quit
Total: 8
Loop through a list of ages and:
[25, -5, 30, 105, 40]
Valid age: 25
Skipped invalid age.
Valid age: 30
VIP detected! Stopping sales.
Check seat availability in a list. Stop when a seat is found, or skip “reserved” seats.
["reserved", "reserved", "available", "reserved"]
Seat 1: Reserved.
Seat 2: Reserved.
Seat 3: Available! Booked successfully.
for
loop in Python is a programming statement that repeats a block of code a fixed number of times.
👉 Learn morewhile
loop in python is a control flow statement that repeatedly executes a block of code until a specified condition is met.
👉 Learn moreelse
clause can be used with loops (for
and while
).
👉 Learn morematch-case
is a modern way to handle data-driven decision-making.
👉 Learn moreTutorials, Roadmaps, Bootcamps & Visualization Projects