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.
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.
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.
... (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.
ποΈ Try It Yourself: Practice Challenges
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.
Given a list of mixed dictionaries containing user data, use continue to skip records missing an 'email' key or having an age below 18.
Create a class named DatabaseConnector containing stubs for connect(), query(), and close() methods using pass so the file compiles cleanly.