Browse Python Topics ▼
Pick a Web Framework

Loop Control Statements

📂 Control Flow 📘 Lesson 16 of 57

Alter and fine-tune loop execution using break, continue, pass, and Python's unique loop else clause.

Under normal conditions, a loop repeats with predictable rhythm: it runs iteration 1, then iteration 2, then iteration 3, until its collection is exhausted or its condition becomes False.

However, real-world software constantly faces unexpected scenarios that require immediate course corrections:

  • You are searching through a database of 500,000 customers. You find the exact customer you need at record #12. Should the computer waste processing power checking the other 499,988 records? No, you want to stop immediately.
  • You are processing a batch of uploaded invoices. Invoice #4 is corrupt or empty. Should the program crash and abandon the rest? No, you want to skip invoice #4 and proceed directly to #5.
  • You are drafting a new loop or function, but have not written the internal logic yet.

Python provides four specialized keywords to manipulate and fine-tune loop execution:

  1. break: The emergency exit—terminates the loop instantly.
  2. continue: The skip button—aborts the current iteration and advances to the next one.
  3. pass: The placeholder—does absolutely nothing, fulfilling indentation syntax.
  4. else: The completion clause—runs code only if the loop completed naturally without hitting a break.

1. The break Statement: Emergency Exit

The break statement terminates the enclosing loop immediately. Execution skips past all remaining iterations and resumes at the first line of code following the loop block.

Example: Stopping a Search Early

fruits = ["apple", "banana", "cherry", "durian", "elderberry"]
target = "cherry"

for fruit in fruits:
    print(f"Checking {fruit}...")
    if fruit == target:
        print(f"--> Target '{target}' found! Halting search.")
        break

print("Search operation concluded.")

Output:

Checking apple...
Checking banana...
Checking cherry...
--> Target 'cherry' found! Halting search.
Search operation concluded.

Notice that "durian" and "elderberry" were never checked. As soon as break fired, the loop stopped dead in its tracks.

break in while True Loops

A very common programming idiom is creating an intentional infinite loop with while True:, using break to exit once a specific condition or user command is met:

# Simulated user input prompt
commands = ["help", "status", "quit", "reload"]
index = 0

while True:
    cmd = commands[index]
    index += 1
    print(f"Received user command: '{cmd}'")
    
    if cmd == "quit":
        print("Exit signal received. Terminating session...")
        break

print("Application safely stopped.")

Output:

Received user command: 'help'
Received user command: 'status'
Received user command: 'quit'
Exit signal received. Terminating session...
Application safely stopped.

[!WARNING] break only exits the innermost loop that contains it. If you have nested loops (a loop inside a loop), breaking inside the inner loop leaves the outer loop running.


2. The continue Statement: The Skip Button

Unlike break, which destroys the loop entirely, continue simply aborts the current iteration. Python discards any remaining code in the loop body for that cycle and jumps immediately to the next iteration.

Example: Processing Only Valid Data

transactions = [120.0, -15.5, 340.0, 0.0, -50.0, 89.9]

print("Processing valid deposits:")
for amount in transactions:
    # Skip negative numbers and zero
    if amount <= 0:
        continue
    
    print(f"  Crediting account: +${amount:.2f}")

Output:

Processing valid deposits:
  Crediting account: +$120.00
  Crediting account: +$340.00
  Crediting account: +$89.90

Flattening Code with Guard Clauses

Without continue, developers often write deeply nested if statements:

# Deep nesting (hard to read)
for item in items:
    if item is not None:
        if item.is_active:
            if item.has_permission:
                process(item)

# Clean, readable guard clauses using continue (Pythonic!)
for item in items:
    if item is None:
        continue
    if not item.is_active:
        continue
    if not item.has_permission:
        continue
    
    process(item)

Using continue as a guard clause keeps your main business logic cleanly left-aligned rather than deeply indented.


3. The pass Statement: The Syntax Placeholder

In Python, indentation defines code blocks. If you write an if statement or loop with an empty body, Python will crash with an IndentationError: expected an indented block.

The pass keyword is a null operation (a “no-op”). When Python encounters pass, it does literally nothing. It simply satisfies Python’s grammar requirements:

# Valid Python: pass acts as an empty placeholder
for num in range(5):
    if num == 2:
        # TODO: Handle special event for number 2 in future release
        pass
    else:
        print(f"Standard number: {num}")

Output:

Standard number: 0
Standard number: 1
Standard number: 3
Standard number: 4

Common uses of pass:

  • Stubbing empty functions or classes during initial architectural design.
  • Ignoring specific exceptions in try ... except blocks.

4. The Pythonic Unique: The Loop else Clause

Most programmers know else from if ... else. But Python has a unique, powerful feature: loops can have an else clause too!

for item in sequence:
    if condition:
        break
else:
    # Runs ONLY if the loop never hit a `break`!

Mental Model: Think “No-Break Victory Lap”

The name else on a loop often confuses newcomers. It helps to think of it as:

“Run this block if the loop ran to completion without hitting any break statement.”

Practical Example: Prime Number Finder

A number is prime if it is greater than 1 and cannot be divided evenly by any number other than 1 and itself:

candidate = 13

# Check if candidate is divisible by any number from 2 up to candidate - 1
for divisor in range(2, candidate):
    if candidate % divisor == 0:
        print(f"{candidate} is NOT prime (divisible by {divisor}).")
        break
else:
    # If the loop finished checking all divisors without hitting break:
    print(f"{candidate} IS a prime number!")

Output:

13 IS a prime number!

If candidate = 9:

  • When divisor = 3, 9 % 3 == 0 evaluates to True.
  • Python prints "9 is NOT prime (divisible by 3)" and executes break.
  • Because the loop broke early, the else block is skipped entirely!

Without the loop else construct, you would have had to invent an auxiliary tracking variable:

# The clumsy non-Pythonic flag variable pattern:
is_prime = True
for divisor in range(2, candidate):
    if candidate % divisor == 0:
        is_prime = False
        break

if is_prime:
    print(f"{candidate} IS prime!")

Python’s loop else eliminates this boilerplate flag variable cleanly.


5. Loop Control Comparison Table

KeywordWhat it doesWhat happens next
breakAborts the entire enclosing loopJumps to code immediately following the loop block
continueSkips the rest of current cycleJumps to next iteration (evaluates condition / next item)
passDoes nothing (syntax placeholder)Continues executing the next line inside the same block
Loop else:Completion blockExecutes only if the loop finishes naturally without break

Summary & Stage 4 Review

Over Stage 4: Control Flow, you have mastered:

  1. Decision branching with if, elif, and else.
  2. Structural deconstruction and pattern matching with match-case.
  3. Automated repetition with for and while loops.
  4. Fine-grained iteration control using break, continue, pass, and else.

With the power to control your code’s path and repeat operations at will, you are ready to dive into storing and organizing structured data in Stage 5, starting with lists.

Test your understanding of Loop Control Statements

Quick interactive practice questions with instant feedback.

Take Quiz →