How to trace Python code by hand
Tracing means predicting exactly what a program prints. Learn the discipline: track variables, follow loops, and evaluate expressions in order.
Code tracing is reading a program like a machine would, step by step. It is the foundation of debugging and of many exam questions.
The method
- Read top to bottom. Statement order matters.
- Track every variable. Write each assignment and update.
- Evaluate expressions in order. Multiplication before addition, left to right for ties.
- Count loop iterations. Ask how many times the body runs.
Example
total = 0
for i in range(4):
total += 1
print(total)
The loop body runs 4 times, so total becomes 4.
Common traps
- Indices start at 0.
%is the remainder,//is floor division.- A loop that never ends is an infinite loop.
Practise with randomised code-tracing questions below.
Put it into practice
Practise this topic with questions and get an explanation after each answer.
Practice this now →