Key Takeaways: Repetition: Loops and Iteration

One-Sentence Summary

Loops let you repeat code without rewriting it — for iterates over a known sequence, while repeats until a condition changes, and the accumulator pattern builds results one iteration at a time.

The Two Loop Types

Loop When to Use Syntax Pattern Key Advantage
for Known number of iterations or iterating over a collection for item in sequence: No manual counter management; clean and concise
while Unknown number of iterations; waiting for a condition while condition: Flexible; handles input validation, menus, searches

range() Quick Reference

Call Produces Note
range(n) 0, 1, ..., n-1 n values starting from 0
range(start, stop) start, start+1, ..., stop-1 Stop value is excluded
range(start, stop, step) start, start+step, ... Step can be negative for counting down

The Accumulator Pattern (Three Steps)

  1. Initialize the accumulator before the loop (e.g., total = 0)
  2. Update the accumulator inside the loop (e.g., total += value)
  3. Use the result after the loop (e.g., print(total))

Works for summing (+= value), counting (+= 1), building strings (+= char), and finding extremes (update if greater/less than current).

Loop Control Statements

Statement Effect Best Use
break Exit the loop immediately Found what you're searching for
continue Skip to the next iteration Invalid data you want to ignore
else (on loop) Runs if loop completes without break Distinguishing "found" vs. "not found"

Common Pitfalls

Pitfall Symptom Fix
Infinite loop Program freezes or repeats endlessly Ensure the while condition will eventually become False
Off-by-one Result is missing the first or last value Check range() start/stop; remember stop is excluded
Accumulator inside loop Final result is only the last value Move initialization before the loop
Wrong loop variable in nesting Inner loop uses outer loop's variable Use descriptive names (row, col) instead of (i, j)

Decision Guide: for vs. while

  • Can you answer "how many times?" before the loop starts? → for
  • Are you waiting for something to happen? → while
  • Iterating over a collection (string, list, etc.)? → for
  • Menu-driven program or input validation? → while

TaskFlow Progress

v0.4: Menu-driven interface with while loop; stores multiple tasks in a list; displays numbered task list with for loop; input validation on task name and priority.

What's Next

Chapter 6: Package your code into reusable functions — def, parameters, return values, and scope.