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.
- 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
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}'")- 1.Lines 4-5: Loops through each character of 'SECURE', printing each with a prefix.
- 2.Line 9: enumerate() wraps the list, starting numbering at 1.
- 3.Lines 10-11: Unpacks (1, 'urgent'), (2, 'free'), etc., and outputs formatted lines.
Character sequence: -> S -> E -> C -> U -> R -> E Indexed indicators: [1] Indicator: 'urgent' [2] Indicator: 'free' [3] Indicator: 'verify' [4] Indicator: 'prize'
• 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
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!")- 1.Line 2: range(5) produces 0, 1, 2, 3, 4 (stop is exclusive).
- 2.Line 5: range(2, 11, 2) produces 2, 4, 6, 8, 10.
- 3.Line 9: range(5, 0, -1) counts down from 5 to 1 (stops before 0).
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!
• 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
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.")- 1.Cycle 1: score 5 < 60 (True) -> prints, multiplies score to 10, iteration=2.
- 2.Cycle 2: score 10 < 60 (True) -> prints, multiplies to 20, iteration=3.
- 3.Cycle 3: score 20 < 60 (True) -> prints, multiplies to 40, iteration=4.
- 4.Cycle 4: score 40 < 60 (True) -> prints, multiplies to 80, iteration=5.
- 5.Cycle 5: score 80 < 60 (False) -> loop terminates.
- 6.Line 11: Emits final confirmation.
Cycle 1: Score = 5 Cycle 2: Score = 10 Cycle 3: Score = 20 Cycle 4: Score = 40 Target reached! Final score = 80 in 4 cycles.
• 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
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.")- 1.Lines 4-7: For each score below 75, continue skips print; prints alerts only for 85 and 92.
- 2.Lines 15-20: Searches sample_email. No word is in suspicious_words.
- 3.Line 21: Because break was never hit, the else block executes and confirms clean status.
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.
• 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
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}")- 1.Lines 6-9: Accumulates total_risk to 331 and threat_count to 2.
- 2.Line 11: Calculates mean risk 331 / 6 = 55.17.
- 3.Lines 25-30: For each email, resets matches list and checks each keyword.
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']
• 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
basicModify 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.
Financial Transaction Stream Anomaly & Fraud Detector
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.
- 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.
- 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.
# 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
Chapter summary
Key concepts and syntax cards for review
- 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.
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?