Beginner 10 min

Debug by tracing state

Turn a surprising output into a small reproducible example and find the first wrong state.

Define the discrepancy

Write down the smallest input that still fails, the result you expected, and the result you saw. This separates understanding the requirement from inspecting the code. Keep the original failing example so you can check it after a fix.

How it works

Collect the smallest input that gives a wrong result. Start a table with the expected values and the actual values. Compare each row until you find the first disagreement. That point usually tells you more than the final output alone.

Compare state one line at a time

On each relevant line, record input values, the current index and the next executed branch. Find the first row where the actual state differs from what the algorithm needs. Fix the reason for that divergence and check a nearby passing case too.

Code example

values = [8, 4, 2]
total = 0
for index in range(1, len(values)):
    total += values[index]
    print(index, total)

Check your understanding

The sample should sum every number. What is the first incorrect state, and how would you fix it?

See the example and explanation
Example 1
Given [8, 4, 2]
Answer 14
Example 2
Given [8]
Answer 8

The first loop iteration starts at index 1 instead of index 0. Start at zero, or iterate directly over values when the position is irrelevant. The corrected total is 14.

Open practice problem
Next lessonTest boundaries and edge cases