Lesson · Control Flow
Loops
48 min readLoops
Loops repeat work over iterables or while a condition remains true. Python's `for` loop is especially important because it is built on the iterator protocol rather than on numeric indexes.
Learning goals
- Trace a
forloop overrange(1, 6)and state the values the target takes and the final value oftotal. - Explain how
forconsumes an iterator withiter()andnext(), and why the loop ends whenStopIterationis raised. - Write a
whileloop whose condition reads loop state, and point at the statement that makes it terminate. - Predict the pass count for
range()with one, two, and three arguments, remembering that the stop value is excluded. - Diagnose an accidental infinite loop by finding the state that never changes.
Mental model
The for loop is the iterator protocol in motion: it asks the iterable for an iterator once, pulls one item per pass, and ends when the iterator is exhausted. A while loop has the other shape: it re-evaluates its condition before every pass, so the loop's own state must move toward the moment the condition becomes false.
Mental model
read it top to bottom
iterable ↓ iter() once iterator (remembers its position) ↓ next() → item → run the body → next() again ↓ next() raises StopIteration loop ends cleanly
Core idea
Choosing a loop is choosing who decides the end. for delegates that decision to an iterable: call iter() once, then next() before each pass, and stop when the iterator raises StopIteration. while keeps the decision in the condition, which is re-tested before every pass, so termination depends on the body changing the state that the condition reads.
for
for consumes an iterable by asking it for an iterator with iter() and calling next() on that iterator before each pass. The loop ends quietly when next() raises StopIteration, and every pass rebinds the loop target to the item just produced.
while
while runs its body as long as its condition stays truthy, re-evaluating the condition before every pass. Termination is the body's responsibility: if nothing in the loop's state changes the condition, the loop runs forever.
Iterating over sequences
A for loop requests an iterator and consumes values from it. Prefer iterating over values directly unless the algorithm genuinely needs numeric indexes.
range()
range() describes an arithmetic sequence with start, stop, and step, where start defaults to 0, step defaults to 1, and stop is always excluded. It produces values lazily, so range(1, 6) covers 1 through 5 while using constant memory regardless of length.
Nested loops
Nested loops place one control structure inside another. They are valid but increase the number of execution paths, so extract functions or use early exits when nesting obscures intent.
Loop variables
A loop target is an ordinary binding in the surrounding local scope, not a separate block-scoped variable. After the loop, its final binding can still exist.
Infinite loops
An intentional infinite loop such as while True needs a clear exit, cancellation, or process-lifetime policy. Accidental infinite loops usually come from state that never moves toward termination.
Sentinel loops
A sentinel loop stops when it observes a distinguished value that marks the end of input. Choose a sentinel that cannot be confused with valid data.
Walkthrough
range(1, 6)describes the integers 1 through 5: start 1 is included, stop 6 is excluded, so the summing loop runs five passes andtotalends at 15.- Each pass binds
numberto the next value and runstotal += number, which rebindstotalto the running sum; afterStopIterationends the loop, the namenumberstill holds 5 because loop targets live in the surrounding scope. while attempts:re-tests the int 3 before every pass;3,2, and1are truthy, so the loop printsremaining: 3,remaining: 2,remaining: 1, and thenattempts -= 1reaches 0, which is falsy and ends the loop.- Predict before running: the final value of
total, and how manyremaining:lines thewhileloop prints beforeattemptshits 0.
Experiments to try
- Swap
range(1, 6)forrange(6)and thenrange(1, 6, 2). Predicttotalfor each version before running; the second version adds only 1, 3, and 5. - Change the
whilecondition toattempts > 0:and confirm the output is identical. Then bindattempts = -1and reason about which of the two conditions loops forever. - Remove the
attempts -= 1line, predict what happens to the condition, and stop the runaway process with Ctrl+C. Explain which piece of state stopped moving. - Add an
if number % 2 == 0:guard inside theforloop so only even values accumulate, and predict the newtotalbefore running.
Common mistakes
- Expecting
range(1, 6)to include 6: the stop value is always excluded, so the loop runs five times and code that assumes six passes is off by one. - Writing
range(5, 1)to count down: with the default step of 1 the sequence never moves toward the stop value, so the body runs zero times and no error reports the silence. - Reading the loop target after a loop that never ran: an empty iterable means the body never executed, so the target was never bound and using it raises
NameError. - Forgetting to update the state a
whilecondition reads: if nothing in the body changes the condition's value, the loop never ends, which is whyattempts -= 1is what makeswhile attempts:safe.
Practice: Easy
- Run the summing loop with
range(1, 6),range(6), andrange(1, 6, 2). Predicttotalfor all three before running, then explain each result with the start, stop, and step arguments. - Print
numberinside theforloop, one value per line. State the first and last printed values before running, and name the value thatrangeexcludes. - Set
attempts = 0and run thewhileloop. Predict the number of printed lines before running, then explain why the body never executes.
Practice: Medium
- Replace the summing loop with
total = sum(range(1, 6))and verify both give 15; rewrite the countdown asfor attempts in range(3, 0, -1):with an equivalent print and say which form makes the direction obvious. - Track a second variable
countinside theforloop by incrementing it each pass; after the loop, computetotal / countand explain whycountis still readable and why it holds 5. - Write the same countdown (5 down to 1) once with a
whileloop and once withforand a negative step; list one advantage of each form for a reader.
Practice: Hard
- Design
countdown(start)that prints fromstartdown to 1 using awhileloop. Define the behavior forstart == 0and for negative starts before implementing, then test each boundary. - Build a failure lab with three entries: a
whileloop missing its decrement (run it briefly, then interrupt), aforloop overrange(5, 1)that never runs, and a loop target read after an empty iterable (NameError). For each, predict first, then explain the result with the iterator protocol or the condition re-check. - This lesson hands off to lesson 16 (Loop Control): rewrite the summing loop so it skips odd numbers with
continueand stops early withbreakoncetotalpasses 10. Predict the finaltotaland explain howbreakends the loop without exhaustingrange.
Lesson checklist
- I can trace
range(1, 6)and say which valuesnumbertakes and whattotalends at. - I can explain
forin terms ofiter(),next(), andStopIterationrather than as index arithmetic. - I can write a
whileloop and point at the statement that makes its condition false. - I can predict when
rangeyields zero passes and when a loop target is left unbound.
Remember
Loops repeat work in two shapes: `for` pulls values from an iterator and ends when the iterable is exhausted, while `while` re-tests a condition and ends when that condition turns false. In the worked example the two cooperate with plain state: `range(1, 6)` feeds the summing loop to 15, and `attempts -= 1` is what eventually stops the countdown at 0. When a loop misbehaves, check the iterable first and the condition's state second, because one of those two is almost always where the problem lives.
Interview angles
What is the main purpose of **for**?+
for consumes any iterable: Python calls iter() once, then next() before each pass, and ends the loop when the iterator raises StopIteration. Each pass rebinds the loop target, so the loop code contains no index management and no termination check.
What should you pay attention to when using **while**?+
while re-evaluates its condition before every pass and runs the body only while the result is truthy. The loop's state must eventually make the condition false, which is why the body normally updates the same variable the condition reads.
How does **Iterating over sequences** fit into this lesson?+
A for loop requests an iterator and consumes values from it. Prefer iterating over values directly unless the algorithm genuinely needs numeric indexes.
Why does `range(5, 1)` produce an empty loop?+
Step defaults to 1, so a start of 5 moving toward a stop of 1 never advances and the iterator ends immediately. Counting down needs an explicit negative step, as in range(5, 0, -1), where the stop value is still excluded.