0%

22- Loop Control Statements

Take control of your loops. Stop them early. Skip iterations. Do nothing as a placeholder. Three powerful statements for fine-tuning iteration.

You have a loop. It runs from start to finish, visiting every item or counting every number. But what if you want to stop early? You found what you were looking for. No need to continue. What if you want to skip a specific iteration? You do not want to process that item. What if you need a placeholder for a loop body you will write later? Python gives you three statements for exactly these situations. break to exit the loop entirely. continue to skip the current iteration. pass to do nothing at all. These are loop control statements. They give you fine-grained control over how your loops execute. Use them wisely. They can make your code clearer or more confusing, depending on how you use them.

🕯️ Magic Note

Unlike many other languages, Python does not have a goto statement or a labeled break. The designers of Python intentionally kept loop control simple. break exits only the innermost loop. If you need to exit multiple nested loops, you need a flag variable or to wrap the loops in a function and use return.

The break Statement (Exit the Loop)
When break is executed, the loop stops immediately. No further iterations are run. Python jumps to the code after the loop.

Python

# break in a for loop

for num in range(1, 101):

if num ** 2 > 50:

break

print(f”{num}^2 = {num**2}”)

# Output:

# 1^2 = 1

# 2^2 = 4

# 3^2 = 9

# 4^2 = 16

# 5^2 = 25

# 6^2 = 36

# 7^2 = 49

# (Stops at 8^2 = 64, no output)

💡 Use break when you have found what you are looking for. Do not keep looping unnecessarily. It saves time and makes your intent clear.
break in a while Loop
The same behavior applies to while loops. break exits immediately.

Python

# Searching a list with break

fruits = [“apple”, “banana”, “cherry”, “date”, “elderberry”]

target = “cherry”

i = 0

found = False

while i < len(fruits):

if fruits[i] == target:

found = True

break

i += 1

if found:

print(f”Found {target} at index {i}”)

else:

print(f”{target} not found”)

🕯️ Magic Note

The combination of while True and break is a common pattern for loops that should run until a condition in the middle becomes true. This is sometimes called “loop and a half” because the exit condition is not at the top or bottom but inside.

Python

# Loop and a half pattern

while True:

name = input(“Enter your name (or ‘quit’ to exit): “)

if name == “quit”:

break

print(f”Hello, {name}!”)

# This loop checks the exit condition in the middle

The continue Statement (Skip to Next Iteration)
When continue is executed, the current iteration stops immediately. Python jumps to the next iteration of the loop. The loop does not end; it just skips the rest of the current pass.

Python

# Print only odd numbers using continue

for num in range(1, 11):

if num % 2 == 0:

continue

print(num, end=” “)

# Output: 1 3 5 7 9

# Skip empty strings

words = [“hello”, “”, “world”, “”, “python”, “magic”]

for word in words:

if word == “”:

continue

print(f”Processing: {word}”)

⚠️ Be careful with continue in while loops. If you skip the statement that updates the condition variable, you may create an infinite loop.

Python

# Danger: infinite loop with continue

x = 0

while x < 10:

if x % 2 == 0:

continue # x never changes when x is even!

print(x)

x += 1

# This loop will never reach x += 1 when x is 0

# Correct way: update before continue or use for loop

for x in range(10):

if x % 2 == 0:

continue

print(x)

break vs continue Comparison
These two statements are often confused. Here is a clear comparison.
breakcontinue
Exits the entire loop immediatelySkips only the current iteration
Loop stops completelyLoop continues with next item
Used when you found what you needUsed when you want to skip certain items
Example: searching, game overExample: filtering, skipping invalid data

Python

# Visual comparison

for i in range(1, 6):

if i == 3:

break

print(i, end=” “)

# Output: 1 2 (loop stops at 3)

for i in range(1, 6):

if i == 3:

continue

print(i, end=” “)

# Output: 1 2 4 5 (3 is skipped)

The pass Statement (Do Nothing)
pass is a placeholder. It does absolutely nothing. It is used when Python expects an indented block but you have nothing to put there yet.

Python

# Empty loop (placeholder)

for i in range(10):

pass # TODO: implement later

# Empty function

def not_ready_yet():

pass

# Empty class

class MyClass:

pass

# In a conditional (placeholder)

error_code = 200

if error_code == 200:

pass # Success – do nothing

else:

print(f”Error: {error_code}”)

🕯️ Magic Note

pass is unique to Python (and a few other languages). It is useful for stub functions, empty classes, and loops that will be filled later. Unlike a comment, pass is actual executable code. It just does nothing.

💡 Use pass as a temporary placeholder while designing your program structure. Remove it when you add the real logic. Never leave pass in production code except for empty classes or abstract methods.
Nested Loops and break
break only exits the innermost loop. It does not break out of outer loops.

Python

# break only affects the inner loop

for i in range(3):

print(f”Outer loop: {i}”)

for j in range(5):

if j == 2:

break

print(f” Inner: {j}”)

print(“Inner loop ended, outer continues”)

# Output shows outer loop runs 3 times

# Each inner loop only prints j=0,1 then breaks

⚠️ return[/highlight]. Or use for-else with nested breaks. The flag variable approach is the most common and readable.

Python

# Breaking out of nested loops with a flag

found = False

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

target = 5

for row in matrix:

for col in row:

if col == target:

found = True

break

if found:

break

print(f”Found {target}!” if found else “Not found”)

The else Clause with break
The else clause in a loop runs only if the loop completes without a break. This creates a clear “found vs not found” pattern.

Python

# Elegant search with for-else

numbers = [1, 3, 5, 7, 9]

target = 4

for num in numbers:

if num == target:

print(f”Found {target}”)

break

else:

print(f”{target} not found”)

# This pattern works with while as well

Practical Example: Input Validation with break
Combine while True with break for robust input validation.

Python

# Keep asking until valid input

while True:

try:

age = int(input(“Enter your age: “))

if 0 <= age <= 120:

break

print(“Age must be between 0 and 120”)

except ValueError:

print(“Please enter a valid number”)

print(f”Age: {age}”)

Common Mistakes with Loop Control
  • Using break when you meant continue (exits instead of skipping)
  • Using continue in a while loop and skipping the increment (infinite loop)
  • Expecting break to exit all nested loops (it only exits the innermost)
  • Using pass when you actually need a comment
  • Leaving pass in production code accidentally
  • Forgetting that else runs when no break occurs
Check Your Understanding
  • What is the difference between break and continue?
  • Write a loop that prints numbers from 1 to 10 but stops at 7 using break.
  • Write a loop that prints only even numbers from 1 to 10 using continue.
  • What does pass do? Give an example of when to use it.
  • How do you break out of multiple nested loops?
  • What triggers the else clause in a loop?

⚡ Whisper

Three small words. break. continue. pass. Each one a tiny spell. break is the escape door. It lets you leave the loop when you have found what you seek. No extra steps. No wasted time. continue is the skip stone. It lets you jump over what you do not need and move to the next. pass is the silence. It does nothing, but it holds the space for something you will write tomorrow. Use these spells well. break too soon and you miss what comes after. continue too much and your logic becomes a maze. pass forever and nothing ever happens. Balance is the key. Know when to stop. Know when to skip. Know when to wait. These are not just loop controls. They are lessons in patience and precision.

Related posts