Ch 05Loops and Repetition
Chapter 05 of 08·20 min

Loops and Repetition

Computers excel at executing repetitive computations millions of times with unflinching precision. Whether iterating through thousands of email records, calculating statistical sums across tabular datasets, or running simulated time steps, loops are essential. In this chapter, you will master Python's loop constructs: definite iteration with for-loops and the range() generator, condition-driven iteration with while-loops, loop control flow using break and continue, the unique loop-else construct, and the accumulator pattern.

Learning objectives
  • 01Execute definite iteration across sequences using for loops and the memory-efficient range() generator
  • 02Implement indexed sequence iteration cleanly using the built-in enumerate() function
  • 03Construct condition-driven while loops with safe state transitions to eliminate infinite loops
  • 04Alter execution flow dynamically using break (early termination) and continue (step bypass)
  • 05Utilize Python's unique loop-else construct to implement clean search and validation algorithms
  • 06Identify and prevent critical edge cases: mutating sequences during iteration, off-by-one range bounds, and infinite loop traps

5.1 The for Loop: Iterating Over Sequences

Python's `for` loop is fundamentally an **iterator loop**. Unlike C or Java where a loop increments an index counter (`for (int i=0; i<n; i++)`), Python's `for` loop directly pulls items from any iterable sequence (string, list, tuple, range): ```python for item in sequence: # execute block for each item ``` Each iteration assigns the next element in the sequence to the target variable `item` and executes the indented 4-space block.
Statement 1: The for Loop and enumerate()

Iterating through characters and using enumerate() to obtain index-element pairs.

# Iterating directly over characters in a string
keyword = "SECURE"
print("Character sequence:")
for char in keyword:
    print(" ->", char)

# Using enumerate() to get zero-based index AND element simultaneously
sample_indicators = ["urgent", "free", "verify", "prize"]
print("\nIndexed indicators:")
for idx, indicator in enumerate(sample_indicators, start=1):
    print(f"[{idx}] Indicator: '{indicator}'")
Execution walkthrough
  1. 1.Lines 4-5: Loops through each character of 'SECURE', printing each with a prefix.
  2. 2.Line 9: enumerate() wraps the list, starting numbering at 1.
  3. 3.Lines 10-11: Unpacks (1, 'urgent'), (2, 'free'), etc., and outputs formatted lines.
Expected output
Character sequence:
 -> S
 -> E
 -> C
 -> U
 -> R
 -> E

Indexed indicators:
[1] Indicator: 'urgent'
[2] Indicator: 'free'
[3] Indicator: 'verify'
[4] Indicator: 'prize'
Edge cases

• Modifying a list during iteration: Never append or remove elements from a list while iterating over it! Removing an element shifts subsequent items left, causing the loop to skip the next item entirely. If you must modify, iterate over a copy: `for item in my_list.copy():`. • Loop variable leakage: In Python, the loop variable (`char` or `indicator`) remains accessible in the outer scope even after the loop finishes! Be careful not to accidentally reuse variable names.

Why it happens: Python objects implementing the __iter__() protocol yield elements sequentially until StopIteration is raised.

5.2 The range() Generator: Numerical Sequences

When you need to execute code a specific number of times, Python provides the built-in `range()` function. ### Three Modes of range(): 1. **`range(stop)`**: Generates integers from `0` up to `stop - 1`. E.g., `range(5)` -> `0, 1, 2, 3, 4`. 2. **`range(start, stop)`**: Generates integers from `start` up to `stop - 1`. E.g., `range(2, 6)` -> `2, 3, 4, 5`. 3. **`range(start, stop, step)`**: Generates integers incrementing by `step`. E.g., `range(0, 10, 2)` -> `0, 2, 4, 6, 8`. *(Note: `range()` is lazy and memory efficient: it calculates numbers on the fly and takes $O(1)$ memory regardless of whether the range spans 10 or 10,000,000 numbers.)*
Statement 2: Generating Ranges & Negative Step Countdowns

Generating stepped sequences, ranges, and backwards countdown loops.

# Standard range (0 to 4)
print("range(5) output:", list(range(5)))

# Start, stop, step
print("Even numbers (2 to 10):", list(range(2, 11, 2)))

# Countdown using negative step
print("Countdown:")
for count in range(5, 0, -1):
    print(f" T-minus {count}...")
print(" BLASTOFF: Simulation Started!")
Execution walkthrough
  1. 1.Line 2: range(5) produces 0, 1, 2, 3, 4 (stop is exclusive).
  2. 2.Line 5: range(2, 11, 2) produces 2, 4, 6, 8, 10.
  3. 3.Line 9: range(5, 0, -1) counts down from 5 to 1 (stops before 0).
Expected output
range(5) output: [0, 1, 2, 3, 4]
Even numbers (2 to 10): [2, 4, 6, 8, 10]
Countdown:
 T-minus 5...
 T-minus 4...
 T-minus 3...
 T-minus 2...
 T-minus 1...
 BLASTOFF: Simulation Started!
Edge cases

• Empty Ranges: If start >= stop with a positive step (e.g. range(5, 2)), Python returns an empty range without throwing an error! The loop simply executes 0 times. • Off-By-One Errors: To loop 10 times from 1 to 10 inclusive, you must write `range(1, 11)`. Writing `range(1, 10)` only runs through 9.

Why it happens: range() implements a sequence type calculating elements via arithmetic arithmetic progression.

5.3 The while Loop: Condition-Driven Repetition

While a `for` loop executes across a known sequence, a `while` loop runs **indefinitely as long as a boolean condition remains True**. ### The Three Components of a Correct while Loop: 1. **Initialization**: Initialize state variables before the loop begins. 2. **Evaluation**: The loop tests the condition before every iteration. 3. **State Mutation**: The loop body **must update the state** so the condition eventually becomes False. *If the state variable is never updated, the loop runs forever, creating an **infinite loop** that hangs the program.*
Statement 3: The while Loop with State Mutation

Simulating exponential growth and queue processing.

# Simulating exponential risk score accumulation
current_score = 5
THRESHOLD = 60
iteration = 1

while current_score < THRESHOLD:
    print(f"Cycle {iteration}: Score = {current_score}")
    current_score = current_score * 2  # State update!
    iteration += 1                     # Increment cycle counter

print(f"Target reached! Final score = {current_score} in {iteration - 1} cycles.")
Execution walkthrough
  1. 1.Cycle 1: score 5 < 60 (True) -> prints, multiplies score to 10, iteration=2.
  2. 2.Cycle 2: score 10 < 60 (True) -> prints, multiplies to 20, iteration=3.
  3. 3.Cycle 3: score 20 < 60 (True) -> prints, multiplies to 40, iteration=4.
  4. 4.Cycle 4: score 40 < 60 (True) -> prints, multiplies to 80, iteration=5.
  5. 5.Cycle 5: score 80 < 60 (False) -> loop terminates.
  6. 6.Line 11: Emits final confirmation.
Expected output
Cycle 1: Score = 5
Cycle 2: Score = 10
Cycle 3: Score = 20
Cycle 4: Score = 40
Target reached! Final score = 80 in 4 cycles.
Edge cases

• Infinite Loops: Forgetting to update `current_score` leaves the score at 5 forever, creating an infinite loop. Always ensure the loop variable moves toward the termination condition on every cycle. • Halting Stuck Execution: If your code accidentally enters an infinite loop, click the 'Stop' button in the editor toolbar to halt execution immediately.

Why it happens: The while loop tests the condition before entering the body. If initial condition is False, it executes 0 times.

5.4 Loop Controls: break, continue, and the Loop-else Construct

Python provides granular controls to alter loop execution: - **`break`**: Immediately aborts and terminates the innermost loop, jumping to the statement following the loop. - **`continue`**: Immediately aborts the **current iteration**, skipping any remaining statements in the body, and jumps to the next iteration. ### Python's Unique `for...else` / `while...else` Construct: An `else` block attached to a loop executes **ONLY if the loop finished naturally without encountering a `break` statement**! This elegant syntax eliminates the need for manual boolean flag variables like `found = False` when searching through sequences.
Statement 4: Using break, continue, and Loop-else

Filtering invalid records with continue and searching with break and loop-else.

# 1. continue: Skipping benign messages
message_scores = [12, 0, 85, 4, 92, -1, 45]
print("Flagging critical messages (> 75):")
for score in message_scores:
    if score < 75:
        continue  # Skip scores below threshold
    print(f" [!] Alert triggered for risk score: {score}")

# 2. break with for...else (Search Pattern)
suspicious_words = ["urgent", "wire", "compromise"]
sample_email = ["meeting notes", "lunch order", "budget review"]

print("\nScanning sample email:")
for word in sample_email:
    if word in suspicious_words:
        print(f" THREAT DETECTED: Found '{word}'!")
        break
else:
    # Executes ONLY if loop finished with NO break
    print(" SCAN COMPLETE: No threats detected across sample.")
Execution walkthrough
  1. 1.Lines 4-7: For each score below 75, continue skips print; prints alerts only for 85 and 92.
  2. 2.Lines 15-20: Searches sample_email. No word is in suspicious_words.
  3. 3.Line 21: Because break was never hit, the else block executes and confirms clean status.
Expected output
Flagging critical messages (> 75):
 [!] Alert triggered for risk score: 85
 [!] Alert triggered for risk score: 92

Scanning sample email:
 SCAN COMPLETE: No threats detected across sample.
Edge cases

• break in Nested Loops: A `break` statement only terminates the innermost loop. The outer loop continues executing. If you need to exit multiple nested loops, wrap them in a function and use `return`.

Why it happens: The loop-else syntax directly models algorithmic search: 'look for target; if not found anywhere, do fallback'.

5.5 The Accumulator Pattern & Nested Loops

In data analysis and AI, the **Accumulator Pattern** is the most widely applied algorithm pattern. You initialize an accumulator variable before a loop (e.g., `total = 0`, `count = 0`, `matches = []`), iterate over data, update the accumulator during each step, and inspect the aggregate value after the loop. When data has dimensions (like rows and columns in a spreadsheet or pixels in an image), **nested loops** (a loop inside a loop) are used.
Statement 5: The Accumulator Pattern and Nested Loops

Calculating statistical aggregates and scanning 2D email batches.

# Accumulator: Summing and calculating average risk
risk_values = [45, 82, 12, 94, 65, 33]
total_risk = 0
threat_count = 0

for val in risk_values:
    total_risk += val  # Accumulate sum (total_risk = total_risk + val)
    if val >= 70:
        threat_count += 1

average_risk = total_risk / len(risk_values)
print(f"Total Risk Sum : {total_risk}")
print(f"Average Risk   : {average_risk:.2f}")
print(f"Threats (>=70) : {threat_count}")

# Nested loop: scanning batch of emails against keyword list
inbox = [
    "Urgent password reset needed",
    "Quarterly review meeting at 2pm",
    "Claim your free prize now"
]
keywords = ["urgent", "free", "prize"]

print("\nNested Scan Results:")
for i, email in enumerate(inbox, start=1):
    matches = []
    for kw in keywords:
        if kw in email.lower():
            matches.append(kw)
    print(f"Email {i}: {len(matches)} match(es) -> {matches}")
Execution walkthrough
  1. 1.Lines 6-9: Accumulates total_risk to 331 and threat_count to 2.
  2. 2.Line 11: Calculates mean risk 331 / 6 = 55.17.
  3. 3.Lines 25-30: For each email, resets matches list and checks each keyword.
Expected output
Total Risk Sum : 331
Average Risk   : 55.17
Threats (>=70) : 2

Nested Scan Results:
Email 1: 1 match(es) -> ['urgent']
Email 2: 0 match(es) -> []
Email 3: 2 match(es) -> ['free', 'prize']
Edge cases

• Resetting Accumulators in Wrong Scope: If you initialize `matches = []` outside the outer loop, matches would accumulate across all emails combined instead of resetting per message! Always place accumulator variables in the exact scope where their lifetime belongs.

Why it happens: The inner loop runs to completion for every single step of the outer loop.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 5: Counting Threat Messages in a Stream

basic

Modify the starter code to iterate through the scores list using a for loop, count how many scores exceed 70 using the accumulator pattern, and print the final count.

Chapter 05 assignmentMilestone

Financial Transaction Stream Anomaly & Fraud Detector

Scenario

A banking fraud monitoring service at the Center of Excellence streams sequential financial transactions for automated risk surveillance. You must build an anomaly detector that processes the stream sequentially, calculates running aggregates, flags outlier spikes, and aborts processing if a critical fraud sequence is detected.

Implementation requirements
  • Given transaction amounts: [150.0, 320.5, 45.0, 12500.0, 240.0, 2100.0, 2800.0, 3200.0, 85.0]
  • Maintain accumulators for: total_volume, valid_transaction_count, and high_value_count.
  • Outlier Rule: If any single transaction exceeds $10,000.0, print an alert '[ALERT] Single high-value transaction detected: $X', increment high_value_count, and use 'continue' to skip adding it to standard volume.
  • Lockdown Rule: If 3 consecutive transactions each exceed $2,000.0, trigger an immediate fraud lockdown alert: '[CRITICAL LOCKDOWN] Consecutive spike threshold breached. Halting stream.', and terminate the loop immediately with 'break'.
  • Use 'for...else' to print '[STATUS] Stream processing completed normally.' if no lockdown occurred.
  • Print final summary statistics: Total Standard Volume, Valid Transaction Count, and High-Value Outlier Count.
Edge cases to handle
  • 1.Consecutive counter reset: If a transaction does NOT exceed $2,000, the consecutive spike counter must be reset to 0!
  • 2.Break vs Else: Ensure the 'else' block does not execute if the loop is aborted via 'break'.
  • 3.Floating-point formatting: Format currency values to 2 decimal places with commas.
Starter template
# Chapter 5 Assignment: Financial Transaction Stream Anomaly Detector
# Center of Excellence: Data Science & AI

transactions = [150.0, 320.5, 45.0, 12500.0, 240.0, 2100.0, 2800.0, 3200.0, 85.0]

total_volume = 0.0
valid_count = 0
high_value_count = 0
consecutive_spikes = 0

# TODO: Iterate through transactions
# TODO: Implement > 10000.0 check with continue
# TODO: Implement consecutive > 2000.0 check with break
# TODO: Accumulate volume and counts
# TODO: Use for...else block
# TODO: Print final summary statistics
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01The for-loop iterates through sequences automatically; enumerate() provides index-value pairs.
  • 02range(start, stop, step) generates memory-efficient numeric progressions without storing all numbers in RAM.
  • 03The while loop evaluates a condition before each cycle; loop state variables must update monotonically.
  • 04break terminates loop immediately; continue skips to the next cycle.
  • 05The loop-else construct executes only if the loop terminates naturally without hitting a break.
Syntax reference
for item in sequence: ...Definite iteration through any iterable sequence.
for idx, val in enumerate(items, start=0): ...Indexed sequence traversal.
while condition: ...Indefinite iteration continuing while condition is True.
for x in items: ... else: ...Executes else block only if no break occurred.

Knowledge check

Verify your grasp of the chapter concepts

What will list(range(3, 12, 3)) produce?

What statement skips the remainder of the current iteration and jumps to the next cycle?

What is the final value of count in: count = 0; while count < 5: count += 2?