Concepts / Debugging Strategies for Finding Errors in Your Code

Debugging Strategies for Finding Errors in Your Code

Semantic errors occur when code runs without error messages but produces incorrect results—the hardest kind of error to catch.

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

When Running Code Is Not Enough

A program can run from beginning to end and still be wrong. This happens when the code follows Python's grammar but does not express the meaning you intended. Such a mistake is called a semantic error. Unlike an error that stops execution, a semantic error may produce ordinary-looking output, so you must compare that output with your expectation.

Syntax errorGrammar is invalidProgram does not runPython refuses to executeitSemantic errorMeaning is incorrectUnexpected outputCode runs without a warningcausescauses
What is the difference between code that cannot run because its syntax is invalid and code that runs but does the wrong thing?

The Comma Trap

What do you think happens?

What do you think this statement prints?

  • 1000000

  • 1,000,000

  • 1 0 0

Reveal answer
Answer:

1 0 0

In Python, the commas separate the values 1, 0, and 0. The print function receives three arguments and places a space between them.

python
Output
1 0 0

The commas are not formatting marks for one large integer. They separate three integer values: 1, 0, and 0. Those values become three arguments to print(), and print() displays multiple arguments with spaces between them. The statement is syntactically valid, so Python runs it. Its meaning is nevertheless different from the intended meaning of one million.

1,000,000Comma-separated values1Integerprint()Three arguments1 0 0Spaces between arguments0Integer0Integerseparatesseparatesseparatesargumentargumentargumentdisplays
How can valid code produce unexpected output, and which statement creates the incorrect value?

Correct Numeric Literals

To represent one million as one integer, write the digits without commas or spaces. Python also allows underscores in numeric literals for readability. The underscores do not change the value.

python
Output
1000000
1000000
1,000,000Three values1 0 0Three printed arguments1_000_000One integer1000000One printed valueprintsprints
What does Python create when comma-separated values are assigned, and how is that different from writing one integer?

A Reliable Debugging Trace

Debugging a semantic error begins with the difference between what you expected and what the program actually produced. First state the expected result. Then inspect the actual output carefully. Next, trace that output back to the statement that supplied the value or values. In the comma example, the first divergence appears in the written expression 1,000,000: the commas create separate values before print() displays anything. Finally, change the statement and run the test again to verify that the output now matches the expectation.

Expected resultState what should happenActual outputRecord what happenedCompare resultsFind the first differenceTrace statementInspect the value-producingcodeCorrect expressionMatch code to intentionVerified outputRun and check againthencompare withif differentthentest again
What steps should you follow from unexpected output to a confirmed fix?
Worked example

Tracing the First Divergence

A learner intends to print one million but sees 1 0 0.

  1. 1
    State the expectation

    The intended result is the single integer 1000000.

  2. 2
    Inspect the output

    The actual result is 1 0 0, which shows that three values were printed.

  3. 3
    Inspect the statement

    The commas in 1,000,000 separate 1, 0, and 0 rather than formatting one integer.

  4. 4
    Apply the correction

    Replace the comma-separated form with 1000000 or 1_000_000.

  5. 5
    Test again

    Run the corrected statement and verify that it prints 1000000.

Result

The output matches the intention after the numeric expression is corrected.

Mistakes That Hide in Plain Sight

  • Common mistake

    Assuming that familiar written number formatting works unchanged in Python.

    What it looks like
    print(1,000,000)
    Why it fails

    Python treats the commas as separators between values, so print() receives three arguments.

    Do this instead
    Write print(1000000) or print(1_000_000).
  • Common mistake

    Treating successful execution as proof that the program is correct.

    What it looks like

    The program runs and prints 1 0 0, so the statement is accepted as correct.

    Why it fails

    Semantic errors produce no warning even though the result is incorrect.

    Do this instead

    Always compare the actual output with the expected output.

  • Common mistake

    Looking only for error messages.

    What it looks like

    A learner stops debugging because Python did not report an error.

    Why it fails

    Syntax errors are reported immediately, but semantic errors can run to completion.

    Do this instead

    Inspect unexpected output and trace it back to the statement that produced it.

  • Common mistake

    Confusing a syntax error with a semantic error.

    What it looks like

    Forgetting the colon after an if statement is treated as if it were merely a wrong result.

    Why it fails

    A missing colon violates Python's grammar, so Python refuses to run the code.

    Do this instead

    Separate errors that prevent execution from errors that produce an incorrect result.

Practice the Trace

EASY

What will this print? Write your prediction, then explain why the output is correct or incorrect for the intended value.

Hints
  • Ask whether the commas are formatting one integer or separating values.
  • Count the values that print() receives.
  • Compare the actual output with the intended representation of one million.
python
1000000One integer1,000,000First divergence1 0 0Three printed valuesintended asinterpreted as
Where does the program's actual result first diverge from the expected result?

Debugging Checklist

  1. 1
    A syntax error violates Python's grammar and prevents the program from running.
  2. 2
    A semantic error runs without an error message but produces a result different from the intended result.
  3. 3
    In Python, commas separate values; they do not format the digits of one large integer.
  4. 4
    Use 1000000 or 1_000_000 for the integer one million.
  5. 5
    Debug semantic errors by stating the expectation, inspecting the actual output, tracing the first divergence to its statement, correcting the code, and testing again.

Key Takeaways

  • Syntax errors stop execution because the code does not follow Python's grammar.
  • Semantic errors are harder to notice because the code runs but produces an incorrect result.
  • The expression 1,000,000 is interpreted as the separate values 1, 0, and 0.
  • Expected-versus-actual comparison helps locate the first point where a program's behavior diverges.
  • Testing corrected code confirms whether the semantic error has been fixed.

More concepts starting with D