Sciomi uses Google Analytics to measure how the site is used. If you accept, it stores a cookie on your device. If you decline, it stores nothing on your device, but Google may still receive a basic signal that a page was opened. Sign-in and practice progress cookies are always used. No ads are shown. Details in the privacy policy

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

  1. Read top to bottom. Statement order matters.
  2. Track every variable. Write each assignment and update.
  3. Evaluate expressions in order. Multiplication before addition, left to right for ties.
  4. 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 →