Loops and Iteration
Repeat work with for and while loops, choose stopping rules deliberately, and avoid off-by-one, infinite-loop, and mutation-during-iteration bugs.
Before this lesson
Choose between for and while
Reason about range boundaries
Use break and continue sparingly
The short answer
Use for when iterating over an iterable and while when repetition depends on a changing condition. Define the loop invariant, stopping rule, and empty-input behavior before coding. Prefer direct iteration over manual indexes.
Build the mental model
A for loop asks an iterable for successive values. range(start, stop, step) excludes stop, which makes it fit zero-based indexing but creates boundary mistakes when guessed. enumerate supplies both positions and values without maintaining a counter.
The central idea in this lesson is controlled repetition. Read the rule, predict a concrete outcome, and then run the smallest example that can confirm or reject the prediction. This separates knowledge from familiarity with syntax.
Make the design choice explicit
A while loop is appropriate for retry, sentinel, or state-driven processes. Ensure something in the body can make its condition false. Break exits the nearest loop; continue begins the next iteration, but too many control jumps can obscure the main rule.
temperatures = [18.5, 21.0, 19.5, 24.0]
total = 0.0
for position, value in enumerate(temperatures, start=1):
print(f"Reading {position}: {value:.1f}°C")
total += value
print(f"Average: {total / len(temperatures):.1f}°C")Expected output
Reading 1: 18.5°C Reading 2: 21.0°C Reading 3: 19.5°C Reading 4: 24.0°C Average: 20.8°C
Trace the example before running it. Identify each input, transformation, returned value, and side effect. Then change one boundary value and explain why the new behavior follows from the rule rather than memorizing the output.
Recognize failure modes
Do not remove items from a list while iterating over that same list. Build a filtered result or iterate over a copy. Test zero iterations, one iteration, the final boundary, and early termination.
Use a professional practice loop
Turn the concept into a repeatable workflow: write down the expected behavior, implement one coherent change, run a representative example, and retain a regression check. If the result surprises you, capture the exact input and error before changing anything.
Review the program for names, boundaries, and hidden side effects. A solution is complete when another developer can understand its contract, reproduce its setup, and verify both the successful path and one meaningful failure path.
Quick knowledge check
Answer before you reveal.
01When is while preferable to for?
When repetition is governed by a changing condition rather than consuming a known iterable.
02What four steps make the practice loop reliable?
Predict the behavior, make one coherent change, run it, and retain a check that detects regression.
Exercise
Practice challenge
Process a list of daily steps, print each numbered reading, and report the total, maximum, and average without using sum or max.
Requirements
- The successful path produces the documented result
- At least one boundary or invalid case is handled deliberately
- Calculation or domain logic is separated from console interaction
Optional extension: Add one automated regression check for the most important rule.
Open in Python compilerLesson checkpoint
One small step locks it in
Mark this lesson complete, then keep the momentum going.
Clear up the details
Frequently asked questions
Is controlled repetition only important in large programs?
No. Small programs reveal the same rules with less noise, and learning the rule early prevents fragile habits from becoming architecture.
Should I memorize every API used here?
No. Memorize the mental model and how to verify behavior. Use documentation for exact names and parameters when needed.
How do I know the exercise is finished?
Meet every success criterion, test at least one boundary or failure case, and explain why the output follows from the code.