Concepts / Debugging Techniques for Loops

Debugging Techniques for Loops

A while loop repeats code as long as a condition is true, checking the condition before each iteration.

  • Programming
Interactive lab

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

  1. State the expected output from the specification, run the program and compare: a difference is the evidence you debug from.
  2. 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.
  3. An inserted print('debug: ...', value) shows the same state in the output; it must not change what the program itself prints.
  4. 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.
  5. 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.

Educational simulation

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.

ConditionTrue or FalseLoop bodyOne iterationNext statementAfter the looptruecheck againfalse
When is the condition evaluated, and what path does execution take when it is true or false?

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.

CheckValue of nCondition n > 0ResultChange in the body
Before iteration 15TrueBody runsn becomes 4
Before iteration 24TrueBody runsn becomes 3
Before iteration 33TrueBody runsn becomes 2
Before iteration 42TrueBody runsn becomes 1
Before iteration 51TrueBody runsn becomes 0
After iteration 50FalseLoop stopsThe next statement runs

Manual trace of the source countdown example

n = 5n > 0: truen = 4n > 0: truen = 3n > 0: truen = 2n > 0: truen = 1n > 0: truen = 0n > 0: falsedecrease ndecrease ndecrease ndecrease ndecrease n
What happens to the condition, loop body, and iteration variable at each step of the countdown?

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

Definition

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.

Worked example

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?

  1. 1
    Locate the initial value

    The first condition check uses n equal to 5, so the condition is true and the body runs.

  2. 2
    Follow the repeated change

    Each iteration decreases n by 1, producing the sequence 5, 4, 3, 2, 1, and then 0.

  3. 3
    Apply the condition

    When n equals 0, n greater than 0 is false. The body does not run for n equal to 0.

Result

The loop has five iterations and stops at the condition check after n becomes 0. The statement after the loop then runs.

5condition true4condition true3condition true2condition true1condition true0condition falsesubtract 1subtract 1subtract 1subtract 1subtract 1
Which value change makes the condition false, and after which iteration does the loop stop?

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.

n > 0truePrint nloop bodyCondition checksame true result if n isunchangedChange nmove toward falseLoop exitscondition falsetruethencheck againrepeatfalse
How does control flow continue when the condition never becomes false, and where should the iteration variable change?
  • Common mistake

    Assuming that a loop stops just because the body has run several times.

    What it looks like

    The condition is checked before every iteration, so the loop continues as long as that check remains true.

    Why it fails

    The number of completed iterations does not by itself make a while loop stop.

    Do this instead

    Trace the iteration variable and evaluate the condition after every body execution.

  • Common mistake

    Forgetting to change the iteration variable.

    What it looks like

    A loop continues while n is greater than 0 but only prints n.

    Why it fails

    If n remains greater than 0, every condition check produces the same true result.

    Do this instead

    Make 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 like

    A condition requires n to become 0 or less, but the loop body changes n away from that range.

    Why it fails

    The condition can remain true forever when the variable does not move toward termination.

    Do this instead

    Compare the direction of the variable's change with the condition before running the loop.

A Manual Debugging Routine

  1. 1
    Write down the iteration variable's initial value.
  2. 2
    Evaluate the loop condition before the first iteration.
  3. 3
    If the condition is true, record that the loop body executes once.
  4. 4
    Record how the loop body changes the iteration variable.
  5. 5
    Evaluate the condition again using the new value.
  6. 6
    Continue 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

EASY

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?

  • The body executes for n equal to 3, 2, and 1, then the loop stops at n equal to 0.

  • The body executes for n equal to 3, 2, 1, and 0.

  • The loop never stops because n is checked before the body.

Reveal answer
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

  1. 1
    A while loop checks its condition before every iteration.
  2. 2
    A true condition runs the loop body; a false condition exits the loop.
  3. 3
    An iteration is one complete execution of the loop body.
  4. 4
    The iteration variable must change toward a value that makes the condition false.
  5. 5
    A 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.

Related concepts

More concepts starting with D