The for Loop: Iterating Over Sequences
A while loop repeats code as long as a condition is true, checking the condition before each iteration.
Try it: Loop Tracer
How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.
How it works
- Initialise the accumulator before the loop.
- Each iteration, the loop variable takes the next value from the list.
- An if inside the loop decides whether to update the accumulator.
- After the last item the loop ends and the accumulator holds the answer.
Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.
Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.
Loading the simulation…
Why Repetition Needs a Loop
Suppose you need to print the numbers 5, 4, 3, 2, and 1, followed by “Blastoff!”. You could write five separate print statements. But counting down from 1000 would require an impractical number of statements. A loop lets you write a small block of code once and have Python execute it repeatedly, with slight variations each time.
The supplied material focuses on the while loop. A while loop repeatedly executes a block of code as long as a condition remains true. Python checks the condition before every possible execution of the loop body. If the condition is true, the body runs. If the condition is false, the loop stops and the program continues with the next statement.
The Countdown Execution Path
Counting Down from Five
Determine what happens when n starts at 5, the loop continues while n > 0, and the body prints n before decreasing it.
- 1Initial check
Python evaluates the condition with n equal to 5. Because 5 is greater than 0, the condition is true and the loop body runs.
- 2First iteration
The body prints 5 and then decreases n to 4.
- 3Middle iterations
The same process occurs for n equal to 4, 3, 2, and 1. Each value is printed, and n decreases by one.
- 4Final check
After the iteration where n is 1, n becomes 0. Python checks n > 0 again. The condition is false, so the loop exits.
- 5Following statement
After the loop exits, the program prints “Blastoff!”.
The loop prints 5, 4, 3, 2, 1 and then prints “Blastoff!”.
Condition Checks and Iteration Variables
The execution flow has a fixed order. Python first evaluates the condition, which produces either True or False. If the result is False, the loop exits immediately. If the result is True, Python executes the loop body and then returns to the beginning to evaluate the condition again.
An iteration is one complete execution of the loop body. If the body executes five times, the loop has five iterations.
The iteration variable is the variable that changes inside the loop body and eventually causes the condition to become false. In the countdown, n is the iteration variable. The body decreases n so that the value moves toward the condition becoming false.
When the Loop Cannot Finish
An infinite loop occurs when the condition never becomes false. One cause is that the iteration variable never changes. Another cause is that it changes in a direction that keeps the condition true. For example, with a condition such as n > 0, failing to decrease n means that n remains greater than 0, so the loop continues indefinitely.
Common mistake Leaving the iteration variable unchanged
What it looks likeA loop checks whether n > 0 and prints n, but never decreases n.
Why it failsThe condition remains true because n never moves toward zero.
Do this insteadModify the iteration variable inside the body so that it moves toward making the condition false.
Common mistake Changing the variable in the wrong direction
What it looks likeA loop uses n > 0 but changes n so that it becomes larger rather than smaller.
Why it failsThe change keeps the condition true instead of moving toward termination.
Do this insteadCheck whether the update moves the variable toward the condition becoming false.
Common mistake Assuming the body runs before the first condition check
Why it failsA while loop checks its condition before every execution, including the first possible iteration.
Do this insteadTrace the initial condition before counting any iteration.
Common mistake Miscounting iterations
Why it failsAn iteration means one complete pass through the body, not one condition check that returns False.
Do this insteadCount only the times the loop body actually executes.
Manual Tracing for Debugging
When a loop produces unexpected output, trace it one step at a time. Before each possible iteration, write down the current value of the iteration variable and the result of the condition. Then record what the body does and what value the variable has afterward. This exposes the exact point where execution diverges from your expectation.
| Check | Value of n | Condition n > 0 | Body executes? |
|---|---|---|---|
| 1 | 5 | True | Yes |
| 2 | 4 | True | Yes |
| 3 | 3 | True | Yes |
| 4 | 2 | True | Yes |
| 5 | 1 | True | Yes |
| 6 | 0 | False | No |
A manual trace separates condition checks from actual iterations. The sixth check does not create a sixth iteration because the body does not execute.
What do you think happens?
A countdown starts with n equal to 5 and continues while n > 0. How many iterations occur before the condition becomes false?
Reveal answer
5
The body executes when n is 5, 4, 3, 2, and 1. After the fifth iteration, n becomes 0. The next condition check is false, so it exits without a sixth iteration.
Practice the Trace
Create a trace for a countdown whose iteration variable starts at 3, whose condition is that the variable is greater than 0, and whose body decreases the variable by 1. Record the variable's value before each condition check, whether the body runs, and the total number of iterations.
Hints
- List the values tested before the body runs.
- Remember that the condition is checked once more after the final iteration.
- Count body executions, not all condition checks.
A loop is expected to run five times, but its output suggests that it runs six times. Describe the trace information you would write down to find the extra iteration.
Hints
- Record the iteration variable before every body execution.
- Check the value immediately after the fifth body execution.
- Inspect the condition that permits the next pass.
Key Takeaways
- 1A while loop checks its condition before each possible iteration.
- 2A true condition runs the body; a false condition exits the loop and continues with the next statement.
- 3An iteration is one complete execution of the loop body.
- 4The iteration variable must change toward making the condition false.
- 5Manual tracing records the variable and condition at each check and helps reveal logic errors.
At a glance
- A while loop repeats a body while its condition remains true.
- Python checks the condition before every iteration, including the first possible one.
- The iteration variable must move toward making the condition false, or the loop may become infinite.
- Tracing values and condition results helps distinguish iterations from checks and exposes unexpected behavior.