Control Flow Statements & Loop Mechanics
An authoritative reference manual on conditional decision trees (if/elif/else), while loops, for loops, iterator protocol, infinite loops, nested loops, the Python loop else suite, break, continue, pass, assert, and return.
Control flow statements govern conditional branching and iterative repetition in Python programs. This chapter provides an exhaustive theoretical treatment of Boolean decision trees, loop iteration mechanics, the Iterator Protocol, the unique Python loop `else` suite, and guard statements.
2.1. 1. Conditional Decision Statements (if / elif / else)
Definition: Conditional statements evaluate Boolean expressions top-down, using 4-space indentation block scoping to execute specific code branches selectively.
Core Working Principles:
- The `if` Statement: Evaluates a single Boolean condition.
- The `if...else` Statement: Provides an alternate execution block when the condition evaluates to `False`.
- The `if...elif...else` Ladder: Evaluates multiple sequential conditions top-down, executing the first `True` branch and skipping all remaining conditional tests.
score = float(input("Enter Student Score (0-100): "))
# Conditional Branching Ladder
if score >= 90:
grade = 'A+'
status = 'Honors'
elif score >= 75:
grade = 'A'
status = 'First Class'
elif score >= 50:
grade = 'B'
status = 'Pass'
else:
grade = 'F'
status = 'Remedial Required'
print(f"Grade Assigned: {grade} ({status})")
5-Marks Exam Scoring Points
- Python uses 4-space indentation to define block scope instead of curly braces {}.
- The elif ladder halts evaluation immediately after executing the first True conditional branch.
2.2. 2. Iteration Loops, The Iterator Protocol & Loop `else` Suite
Definition: Loops repeat execution while a condition remains true or across sequence items via the Iterator Protocol; Python loops feature a unique `else` suite that executes when loops complete normally.
Core Working Principles:
- `while` Loop: Repeats execution as long as a Boolean test condition evaluates to `True` (supports infinite loops if condition is never invalidated).
- `for` Loop & Iterator Protocol: A `for` loop implicitly obtains an iterator from an iterable object (`iter_obj = iter(iterable)` via `__iter__()`) and calls `next(iter_obj)` (`__next__()`) repeatedly until a `StopIteration` exception is caught.
- Memory Optimization with `range()`: `range(start, stop, step)` creates a lightweight range object that computes values lazily on-demand rather than allocating a full list in RAM.
- The Python Loop `else` Suite: A special code block attached to a `for` or `while` loop that executes **only if the loop completes all iterations normally without encountering a `break` statement**!
Loop Iteration: Searching pockets 1 through 5 sequentially for your house keys.
Break Statement: Finding keys in pocket 2 $ ightarrow$ Stop searching and exit loop immediately!
Loop Else Suite: If you checked all 5 pockets without finding keys $ ightarrow$ Execute the else alarm block: "Keys not found in any pocket!"
graph TD
Start[Start Loop Iteration] --> Cond{Sequence Items Remaining via __next__?}
Cond -->|Yes| Body[Execute Loop Body Code]
Body --> BreakCheck{Break Statement Executed?}
BreakCheck -->|Yes: Abort Loop| Exit[Exit Loop: Skip Else Suite!]
BreakCheck -->|No: Continue| Cond
Cond -->|No: StopIteration Caught| ElseBlock[Execute Loop ELSE Suite Block!]
ElseBlock --> Exit
# Prime Number Search Demonstrating Loop Else Suite
numbers_to_test = [29, 33, 37]
for num in numbers_to_test:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print(f"{num} is Composite (divisible by {i})")
break
else:
# Executes ONLY if inner for loop completed without hitting break
print(f"{num} is a PRIME Number! 🌟")
5-Marks Exam Scoring Points
- The loop else suite executes if the loop runs to natural completion.
- If a break statement is executed, the loop else suite is bypassed entirely.
- range(start, stop, step) generates numbers lazily on-demand to optimize memory usage.
2.3. 3. Jump & Guard Control Statements: break, continue, pass, assert, return
Definition: Guard statements modify normal loop progression, provide syntactical placeholders, validate runtime assertions, or return values from functions.
Core Working Principles:
- `break`: Terminates the enclosing loop immediately and transfers control to the statement following the loop.
- `continue`: Aborts the current iteration step and jumps directly to the next loop evaluation cycle.
- `pass`: Null statement acting as a syntactical placeholder for empty function/class definitions (compiles to a `NOP` bytecode instruction).
- `assert`: Runtime assertion check (`assert condition, 'Error Message'`). Raises `AssertionError` if condition is False.
- `return`: Exits a function immediately, pops the current stack frame, and passes control/values back to the caller invocation site.
| Control Statement | Primary Operational Purpose | Behavioral Impact on Execution |
|---|---|---|
break |
Immediate loop termination | Exits loop completely & skips loop else suite |
continue |
Iteration skip | Jumps directly to next loop evaluation cycle |
pass |
Syntactical placeholder | No-Operation; allows empty code blocks without syntax errors |
assert |
Invariant testing guard | Raises AssertionError if Boolean condition is False |
return |
Function termination | Exits function & passes return object to caller |
def process_positive_even(val):
# Assert Guard Statement
assert val > 0, "Input must be positive!"
if val % 2 != 0:
return None # Return statement
else:
pass # Pass placeholder
return val * 10
# Loop with break & continue
for n in range(1, 10):
if n % 3 == 0:
continue # Skip multiples of 3
if n == 8:
break # Exit loop at 8
print(f"Processed item: {n}")
5-Marks Exam Scoring Points
- pass serves as a syntactical placeholder for empty functions or classes.
- assert validates runtime preconditions, raising AssertionError upon failure.
- return terminates function execution immediately.
✍️ Chapter 2 Reference Exercises & Review Problems
`for i in range(1, 6):`
`if i == 4:`
`break`
`print(i, end=' ')`
`else:`
`print('Finished')`
- **Output:** `1 2 3 `
- **Explanation:** The `for` loop iterates `i = 1` (prints 1), `i = 2` (prints 2), `i = 3` (prints 3). When `i = 4`, `if i == 4` evaluates True and executes `break`. `break` immediately terminates the loop and **bypasses the loop `else` suite**! Thus, `'Finished'` is NEVER printed.
- **`pass`:** A null statement (No-Operation) that acts purely as a syntactic placeholder. It does NOT skip remaining code in the loop body.
- **`continue`:** A control flow statement that aborts the remainder of the current loop body and jumps directly to the next iteration cycle.
- **Example:**
`for i in [1, 2]:`
`pass`
`print(i)` $\rightarrow$ Prints 1 and 2.
`for i in [1, 2]:`
`continue`
`print(i)` $\rightarrow$ Prints NOTHING because `continue` skips `print(i)`!