Control Keywords: break, continue & pass

Module 2 β€’ Session 11 β€’ Allocation: 1 Contact Hr

break continue pass loop flow nested loops

Control flow statements alter the standard sequential execution of loops and code blocks. Python provides three key control keywords: break for early termination, continue for skipping iterations, and pass as a structural placeholder.

1. Summary Comparison

Understanding when and how each keyword alters program flow is essential for clean loop design.

Keyword Action on Loop Execution Common Use Case
break Terminates the nearest enclosing loop immediately. Program control transfers to the statement right after the loop. Early exit when a target item is found or a critical error condition occurs.
continue Aborts the rest of the current iteration's code block and jumps straight to evaluating the next loop iteration condition. Filter out invalid or unwanted items (e.g., skip empty lines, null values, or odd numbers).
pass Does nothing (null operation / no-op). Executes cleanly without changing any loop or conditional state. Syntactic placeholder in unwritten functions, classes, or minimal exception blocks where indentation requires a body.

2. Early Loop Exit with `break`

When Python hits a break statement, it cancels any remaining iterations of the current loop level and proceeds directly to the code below the loop.

data_stream = [12, 45, 99, -1, 30, 88] for val in data_stream: if val < 0: print(f"Negative sentinel value ({val}) encountered. Aborting processing.") break print(f"Processed stream value: {val}") print("Stream consumption halted.")

3. Skipping Iterations with `continue`

The continue statement skips the remainder of the statements in the loop body for the current pass and forces the loop to evaluate its next element or condition immediately.

raw_data = ["Alice", "", "Bob", None, "Charlie", " "] for name in raw_data: # Skip empty or invalid records if not name or not name.strip(): continue print(f"Sending welcome email to: {name.strip()}")

4. The Syntactic Placeholder: `pass`

Python uses whitespace indentation to define code blocks. Empty blocks produce a IndentationError. The pass keyword satisfies the parser when logic is intentional or yet to be implemented.

# Function stub for future development def process_payment_gateway(transaction_id): pass # TODO: Integrate Stripe API next sprint # Class stub class CustomNetworkError(Exception): pass # Minimal conditional logic status_code = 200 if status_code == 200: pass # Everything is fine, take no special action else: print("Alert administrator!")
`pass` vs `Ellipsis (...)`: In modern Python, the literal ... (Ellipsis) can also be used as a placeholder in function stubs or type hints, but pass remains the standard keyword choice for empty block structures.

5. Nested Loops and Scope Boundaries

A critical rule in Python is that break and continue affect only the innermost loop that directly contains them.

for matrix_row in range(1, 4): print(f"--- Starting Row {matrix_row} ---") for matrix_col in range(1, 4): if matrix_col == 2: # Breaks ONLY the inner column loop break print(f"Cell ({matrix_row}, {matrix_col})")
Escaping Outer Loops: If you need to break out of multiple nested loop layers simultaneously, consider placing the nested loops inside a helper function and returning directly, or maintaining a boolean flag variable checked by the outer loop.

πŸ‹οΈ Try It Yourself: Practice Challenges

Challenge 1: Input Validator with Break

Write a loop that continuously asks the user for a numeric score between 0 and 100. Use break to exit the loop when a valid score is supplied.

Challenge 2: Multi-Criteria Data Cleaner with Continue

Given a list of mixed dictionaries containing user data, use continue to skip records missing an 'email' key or having an age below 18.

Challenge 3: Skeleton Class Structure with Pass

Create a class named DatabaseConnector containing stubs for connect(), query(), and close() methods using pass so the file compiles cleanly.

⚑ Interactive Sandbox (Loop Control Engine)
Console Output:
Click "Run Code" above to execute interactive control flow scripts...

πŸ“ Knowledge Check Quiz

Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)