Concepts / Debugging Your Code

Debugging Your Code

A useful debugging habit is to read a script as a sequence of events.

  • 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…

Follow the Execution Order

When a program contains several statements, Python does not execute them all at once. It runs them in order from top to bottom. One statement completes before the next statement begins. This execution order gives you a reliable way to understand what a script will do and to investigate behavior that is not what you expected.

x = 4store 4print(x)display 4x = 9store 9print(x)display 9thenthenthen
What happens next as the script runs from the first statement to the last?

Trace Each Statement

To trace a script, examine each statement in sequence and ask two questions: What does this statement do, and does it produce output? Also note whether it changes a variable. This separates the internal work of the program from the visible result on the screen.

Worked example

Tracing a Value from Start to Finish

Determine what the script displays.

  1. 1
    Statement 1

    The assignment statement stores the value 6 in the variable score. It does not display anything.

  2. 2
    Statement 2

    The print() statement displays the current value of score, which is 6.

  3. 3
    Statement 3

    The assignment statement stores the value 10 in score. The earlier value remains available until this assignment changes the variable, and this assignment itself displays nothing.

  4. 4
    Statement 4

    The print() statement displays the current value of score, which is now 10.

Result

The visible output is 6 followed by 10.

python
Output
6
10
score = 6score becomes 66displayedscore = 10score becomes 1010displayednextnextnext
How does each statement change the current value and determine the output that appears later?

What do you think happens?

What will this script display, in order?

  • 2 followed by 2

  • 2 followed by 7

  • 7 followed by 2

  • Nothing

Reveal answer
Answer:

2 followed by 7

The first print() runs while number has the value 2. The later assignment changes number to 7, and the second print() displays the updated value.

python

Store Values or Display Results

Statement kindMain effectVisible output
Assignment statementStores a value in a variableNo
print() statementDisplays a resultYes

Tracing requires you to distinguish internal value changes from visible output.

An assignment statement changes what value is stored for a variable, but the assignment does not by itself place text on the screen. A print() statement displays a result. Values assigned in earlier statements remain available for later statements, so a later print() can display a value that was stored earlier or a newer value that replaced it.

scorevariableScreenno assignment output10stored valuestores
What changes when a value is assigned, and why does an assignment produce no screen output?
total = 12stores a valuetotalupdated valueprint(total)displays a result12screen outputstoresshows
Which statement changes a stored value, which statement displays a result, and how are their effects different?

Mistakes Beginners Make

  • Common mistake

    Expecting an assignment to display its value

    What it looks like
    value = 25
    Why it fails

    The assignment stores 25 but does not produce visible output.

    Do this instead

    Use print(value) when the value needs to appear on the screen.

  • Common mistake

    Reading the final value into every earlier print() statement

    What it looks like
    amount = 3
    print(amount)
    amount = 8
    print(amount)
    Why it fails

    Each print() runs at its position in the sequence. The first print() runs before amount changes to 8.

    Do this instead

    Trace the current value at each line. The output is 3 followed by 8.

  • Common mistake

    Skipping assignment statements while tracing

    What it looks like
    first = 4
    second = first
    print(second)
    Why it fails

    The second assignment makes a value available to the later print() statement.

    Do this instead

    Record what each assignment stores, even when it produces no output.

  • Common mistake

    Looking only at statements that produce output

    What it looks like
    count = 1
    count = 2
    print(count)
    Why it fails

    The final output depends on the later assignment, even though neither assignment displays anything.

    Do this instead

    Mark both output and value changes while moving from top to bottom.

Practice the Trace

EASY

Trace this script from top to bottom. Write down the value of label after each assignment and predict the exact output.

Hints
  • The first assignment stores a value but displays nothing.
  • The first print() uses the value stored before the next assignment.
  • The second assignment changes the value before the final print().
python
Worked example

Practice Solution

Determine the output of the label script.

  1. 1
    First line

    label receives the value 4. Nothing is displayed.

  2. 2
    Second line

    print(label) displays 4.

  3. 3
    Third line

    label receives the value 11. Nothing is displayed.

  4. 4
    Fourth line

    print(label) displays the current value, 11.

Result

The output is 4 followed by 11.

A Reliable Debugging Routine

  1. 1
    Begin with the first statement and move downward one statement at a time.
  2. 2
    Describe what the current statement does.
  3. 3
    Record whether the statement changes a variable.
  4. 4
    Record whether the statement produces visible output.
  5. 5
    When a print() statement appears, use the value stored at that exact point in the sequence.
  6. 6
    Compare your predicted output with the program's actual output to locate where your understanding differs.

This routine turns debugging into a trace rather than a guess. The important information is not only what a variable contains at the end, but also what it contained when each statement executed. Since statements run sequentially, an earlier print() can display an earlier value even when a later assignment changes that variable.

Key Takeaways

  1. 1
    A script executes statements from top to bottom, with each statement completing before the next begins.
  2. 2
    Assignment statements store values but produce no visible output.
  3. 3
    print() statements display results using the value available when they execute.
  4. 4
    Values stored earlier remain available to later statements until a later assignment changes the variable.
  5. 5
    Line-by-line tracing helps you predict output and locate unexpected behavior.

At a glance

  • Execution proceeds sequentially from the first statement to the last.
  • Assignments change stored values without displaying them.
  • print() displays the current value at its position in the script.
  • Tracing every statement makes multi-statement output predictable.
  • Debugging begins by comparing each statement's effect with the result you expected.

Related concepts

More concepts starting with D