Python Loops Cheat Sheet
Loops let code repeat work: while runs until a condition turns false, for runs once per item in a sequence.
Core Principles
- while: condition-controlled; pretest, so it skips entirely if the condition starts false.
- for: count-controlled; iterates once per item in a sequence or range.
- Count-controlled while needs three parts: initialize, compare, update the counter.
- range(stop), range(start, stop), range(start, stop, step): stop is excluded.
- Accumulator: variable that grows each pass to hold a running total.
- Nested loops: total iterations = inner iterations × outer iterations.
- Input validation loops repeat until input is good, because GIGO: garbage in, garbage out.
Action Steps
- 1. Initialize the accumulator to 0 before the loop (prevents undefined or wrong totals).
- 2. Update the condition variable inside the body (makes the loop eventually stop).
- 3. Use while (score := int(input(...))) < 0: to combine the read and validation.
- 4. Use break to exit early; use else to run code only if no break occurred.
Key Terms
- Iteration: One execution of a loop body; a while loop is a pretest loop.
- Sentinel: Distinct end-marker value, like an empty line in a file, that terminates a loop.
- Counter variable: Variable assigned a new value each iteration, used to count how many times a loop runs.
- Target variable: Variable in a for loop that holds the current item from the sequence each iteration.
- Infinite loop: Loop with no way to make its condition false; runs until the program is interrupted.
Pro Tips
- Prefer for with range when the count is known; the update happens automatically, so you avoid off-by-one bugs.
- Use range(10, 0, -1) for countdowns; the start must exceed the stop and the step must be negative.
- Draw a shape with forward(100) and right(360/n) to close it exactly for any n sides.
Pitfalls to Avoid
- Forgetting to update the condition variable creates an infinite loop, freezing the program until interrupted.
- Placing the counter increment after continue skips it, causing an infinite loop.
- Writing range(0, 5) expects 5 iterations but yields 0 to 4; the end limit is never included.
- Copy-pasting repeated code instead of looping makes programs longer and needs fixes in many places.
- Processing unvalidated input produces bad output with no error, because the computer cannot judge data quality.
Related cheat sheets
More like this