Reference Manual • Chapter 2

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:

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:

🔄 Layman Analogy: Searching for Keys with an Else Alarm

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
                    
Architecture Specification 2.1: Python Loop Iteration, Iterator Protocol & Loop Else Suite Execution
# 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:

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

Exercise 2.1: Analyze the execution output of the following loop script:
`for i in range(1, 6):`
    `if i == 4:`
        `break`
    `print(i, end=' ')`
`else:`
    `print('Finished')`
Step-by-Step Reference Solution:
- **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.
Exercise 2.2: Differentiate between `pass` and `continue` with a code example.
Step-by-Step Reference Solution:
- **`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)`!