Debugging Techniques for Loops
A while loop repeats code as long as a condition is true, checking the condition before each iteration.
Try it: Debug by Tracing Execution
How to debug a program that runs but gives the wrong answer: compare expected and actual output, trace the lines in the order they really run with a variable watch table (or an inserted debug print), find the first line where a value goes wrong, then choose a fix and re-run to check it.
How it works
- State the expected output from the specification, run the program and compare: a difference is the evidence you debug from.
- Trace in execution order, not file order: loops repeat lines, if/elif picks one branch, and the watch table records every variable before each line runs.
- An inserted print('debug: ...', value) shows the same state in the output; it must not change what the program itself prints.
- Look for the first place a value differs from what it should be (an off-by-one range, > instead of >=, a total reset inside the loop, two names for one list, a str from input()). Where the wrong value shows up is only the symptom.
- Change one thing with a reason, re-run, and compare again: a fix that makes an error disappear can still leave the output wrong.
Default run (14 steps): Sum 1..n: Add up the whole numbers from 1 to n (n included) and print the sum. Press Play to trace it line by line. … Finished, but the output is wrong: got sum of 1 to 5 is 10, expected sum of 1 to 5 is 15.
Simplified: The lab's own small Python interpreter runs fixed, hand-written programs (you pick the program, the fix and a value; your text is never executed). Every program the lab can show was run in CPython 3.12 and the lab reproduces its output, its traceback text and its line-by-line trace. Six short programs, one editable value each; input() receives the value you type in the lab. Lines starting with "debug:" are ignored when comparing the output with the expected output.
Loading the simulation…
Why Trace a Loop
A loop is useful when the same task must be repeated. Instead of writing separate instructions for printing 5, 4, 3, 2, and 1, a loop can execute a small block repeatedly while the values change. Debugging a loop means examining those repetitions closely so you can see whether the condition, loop body, and changing variable behave as expected.
A while loop checks its condition before every iteration. If the condition is true, the loop body runs. After the body finishes, control returns to the condition. If the condition is false, the loop stops immediately and the program continues with the statement after the loop.
Tracing the Countdown
Consider a countdown whose variable n starts at 5. The condition is n greater than 0. During each iteration, the current value is printed and n is decreased by 1. The loop body therefore executes once for each value from 5 through 1.
| Check | Value of n | Condition n > 0 | Result | Change in the body |
|---|---|---|---|---|
| Before iteration 1 | 5 | True | Body runs | n becomes 4 |
| Before iteration 2 | 4 | True | Body runs | n becomes 3 |
| Before iteration 3 | 3 | True | Body runs | n becomes 2 |
| Before iteration 4 | 2 | True | Body runs | n becomes 1 |
| Before iteration 5 | 1 | True | Body runs | n becomes 0 |
| After iteration 5 | 0 | False | Loop stops | The next statement runs |
Manual trace of the source countdown example
An iteration is one complete pass through the loop body. In this countdown, the body runs five times, so the loop has five iterations. Notice that the condition is also checked after the fifth pass. The value 0 does not produce another iteration because n greater than 0 is false.
Finding the Terminating Change
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 because its value moves from 5 toward 0.
To predict termination, compare the condition with the direction of change. For n greater than 0, decreasing n moves toward the stopping value 0. Each pass must move the variable closer to a value that makes the condition false. If the variable moves away from that value, or does not move at all, the loop may not terminate.
Predicting the Stop Point
A while loop starts with n equal to 5, continues while n is greater than 0, and decreases n by 1 during each loop-body execution. When does the loop stop?
- 1Locate the initial value
The first condition check uses n equal to 5, so the condition is true and the body runs.
- 2Follow the repeated change
Each iteration decreases n by 1, producing the sequence 5, 4, 3, 2, 1, and then 0.
- 3Apply the condition
When n equals 0, n greater than 0 is false. The body does not run for n equal to 0.
The loop has five iterations and stops at the condition check after n becomes 0. The statement after the loop then runs.
Recognizing Infinite Loops
An infinite loop occurs when its condition never becomes false. One cause is that the iteration variable does not change. Another is that it changes in a direction that keeps the condition true. For example, a loop that continues while n is greater than 0 but only prints n, without decreasing n, will keep finding the same true condition.
Common mistake Assuming that a loop stops just because the body has run several times.
What it looks likeThe condition is checked before every iteration, so the loop continues as long as that check remains true.
Why it failsThe number of completed iterations does not by itself make a while loop stop.
Do this insteadTrace the iteration variable and evaluate the condition after every body execution.
Common mistake Forgetting to change the iteration variable.
What it looks likeA loop continues while n is greater than 0 but only prints n.
Why it failsIf n remains greater than 0, every condition check produces the same true result.
Do this insteadMake sure the loop body changes the iteration variable toward a value that makes the condition false.
Common mistake Changing the iteration variable in the wrong direction.
What it looks likeA condition requires n to become 0 or less, but the loop body changes n away from that range.
Why it failsThe condition can remain true forever when the variable does not move toward termination.
Do this insteadCompare the direction of the variable's change with the condition before running the loop.
A Manual Debugging Routine
- 1Write down the iteration variable's initial value.
- 2Evaluate the loop condition before the first iteration.
- 3If the condition is true, record that the loop body executes once.
- 4Record how the loop body changes the iteration variable.
- 5Evaluate the condition again using the new value.
- 6Continue until the condition becomes false, or identify that the value is not moving toward termination.
Use this routine when a loop produces unexpected output. If you expected five iterations but observed six, a trace can show the extra iteration and the condition value that allowed it. Writing down the variable and condition before each iteration makes the point where execution diverges from your expectation visible.
Practice the Trace
A countdown loop begins with n equal to 3, checks whether n is greater than 0, and decreases n by 1 during each loop-body execution. Record the value of n and the condition result before each iteration. Then state the number of iterations and the value that makes the loop stop.
Hints
- List the values in the order used by the condition checks.
- Separate values that execute the body from the value that only causes the loop to stop.
- Count complete passes through the loop body, not condition checks.
What do you think happens?
What should you predict before checking the trace?
Reveal answer
The body executes for n equal to 3, 2, and 1, then the loop stops when the next condition check finds n equal to 0.
The condition is checked before each iteration. The value 0 makes n greater than 0 false, so it does not produce another loop-body execution.
Key Takeaways
- 1A while loop checks its condition before every iteration.
- 2A true condition runs the loop body; a false condition exits the loop.
- 3An iteration is one complete execution of the loop body.
- 4The iteration variable must change toward a value that makes the condition false.
- 5A step-by-step trace exposes unexpected iterations and helps reveal infinite loops.
At a glance
- A while loop evaluates its condition before each iteration.
- Tracing records the iteration variable, condition result, and body execution in sequence.
- The iteration variable must move toward a value that makes the condition false.
- An infinite loop occurs when the condition never becomes false.
- Manual tracing helps locate unexpected iterations and logic errors.