Concepts / Debugging Your First Program

Debugging Your First Program

A first program becomes easier to understand when you follow it as a sequence of instructions.

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

From Instructions to Output

A first program becomes easier to understand when you follow it as a sequence of instructions. Python runs one statement at a time from top to bottom. A complete program can assign values to variables, modify those values, and display the current results.

What do you think happens?

Before tracing the program, predict the two numeric values that will be displayed and describe what will happen to the multi-line text.

Reveal answer
Answer:

The numeric output is 5 followed by 6. The multi-line text is then displayed with its internal line break preserved.

The first assignment gives i the value 5. The later assignment evaluates i + 1 and stores 6 back in i. The final print displays a string whose line break is part of its value.

i = 5assign 5print idisplay 5i = i + 1assign 6print idisplay 6s = '''...'''assign textprint sdisplay textnextnextnextnextnext
What happens next as Python executes each statement from top to bottom?

Tracing the Variable i

The equals sign in an assignment is an instruction that connects a variable name to a value. In i = 5, Python associates the name i with the value 5. This is not a mathematical equation. Assignment does not produce screen output by itself; output occurs when a print statement asks Python to display a value.

inot assigned5after i = 56after i = i + 1assign 5add 1 and assign
How does the value associated with i change after each assignment statement runs?

The statement i = i + 1 is read in two stages. Python first looks at the current value of i and evaluates the right side. When i contains 5, i + 1 produces 6. Python then assigns that new value back to i, replacing the old value. The variable therefore has a current value that depends on the statements that have already run.

Worked example

Following i One Statement at a Time

Determine the value displayed by each print statement in this sequence.

  1. 1
    Assignment

    i = 5 connects the variable i to the value 5. Nothing is displayed yet.

  2. 2
    First output

    print i reads the current value of i, so it displays 5.

  3. 3
    Modification

    i = i + 1 evaluates to 6 and stores 6 in i.

  4. 4
    Second output

    The next print i reads the updated value, so it displays 6.

Result

The numeric output appears in this order: 5, then 6.

A Complete First Program

Code walkthrough
i = 5
print i
i = i + 1
print i
s = '''First line
Second line'''
print s
  1. 1
    i = 5 assigns the value 5 to i.
  2. 2
    print i displays the current value of i, which is 5.
  3. 3
    i = i + 1 evaluates the current value plus 1 and assigns 6 back to i.
  4. 4
    The second print i displays the updated value, 6.
  5. 5
    The triple-quoted assignment stores text containing two lines in s, including the line break between them.
  6. 6
    print s displays both lines of the string.
Output
5
6
First line
Second line
i55print ii66print istwo-line stringtwo text linesprint sprint readsprint readsprint reads
How does a value move from a variable into the displayed output?

The first print statement sees 5 because the increment has not happened yet. The second print statement sees 6 because the assignment i = i + 1 has already replaced the old value. The final print displays the complete string, including its internal line break.

Multi-Line Text Values

Triple quotes allow a string to span multiple lines. Everything between the opening triple quotes and the closing triple quotes belongs to the string value, including the line break in the middle. A single-line string uses single or double quotes and fits on one line; a triple-quoted string can preserve internal line breaks.

One stringtriple-quoted textTwo output linesline break preservedprint s
How is text containing multiple lines stored in one string and then displayed?
python
Output
First line
Second line

Mistakes in Sequential Programs

  • Common mistake

    Treating i = i + 1 as a mathematical equation.

    What it looks like

    Reading the statement as if i must equal itself plus 1 at the same time.

    Why it fails

    The equals sign performs assignment. Python evaluates the right side using the current value of i and then stores the result back in i.

    Do this instead

    Trace it in two stages: if i is 5, evaluate i + 1 as 6, then assign 6 to i.

  • Common mistake

    Expecting an assignment statement to display a value.

    What it looks like

    Running i = 5 and expecting 5 to appear on the screen.

    Why it fails

    Assignment connects a variable name to a value but does not ask Python to display anything.

    Do this instead

    Use print i when you want to display the current value.

  • Common mistake

    Forgetting that statement order affects output.

    What it looks like

    Moving the first print i after i = i + 1 and still expecting it to display 5.

    Why it fails

    Python executes from top to bottom, so the variable has already changed by the time the moved print statement runs.

    Do this instead

    Record the variable's current value immediately before each print statement.

  • Common mistake

    Treating a multi-line string as if its line break disappears.

    What it looks like

    Expecting print s to place both lines of a triple-quoted string on one output line.

    Why it fails

    The internal line break is part of the string value and is preserved when the string is displayed.

    Do this instead

    Expect the output to follow the line structure written between the triple quotes.

Best practice

When debugging a short program, make a trace before changing code. Write down the current value of each variable after every assignment, then compare that trace with the actual output. If the output differs from your expectation, inspect the statements immediately before the unexpected value appears.

Trace Before You Run

EASY

Trace this program from top to bottom. Write the value of i immediately before each print statement, then write the exact output order.

i = 5
print i
i = i + 1
print i
Hints
  • The first assignment gives i the value 5.
  • The second assignment evaluates the current value of i plus 1.
  • A print statement displays the value that exists at that point in the sequence.
MEDIUM

Create a short program that assigns a two-line string to s with triple quotes and then displays s. Before running it, predict whether the output will appear on one line or two.

Hints
  • Place the line break between the opening and closing triple quotes.
  • Use print s after the assignment.
  • The internal line break is part of the string value.

Key Takeaways

  1. 1
    Python executes statements from top to bottom, one statement at a time.
  2. 2
    Assignment connects a variable name to a value; a later assignment can replace the variable's current value.
  3. 3
    The statement i = i + 1 reads the current value, adds 1, and assigns the result back to i.
  4. 4
    The print statement displays the value a variable has at the moment print runs.
  5. 5
    Triple-quoted strings can contain multiple lines, and their internal line breaks are preserved when displayed.

At a glance

  • A complete Python program combines assignment, modification, and output in a top-to-bottom sequence.
  • A variable does not have one permanent value during execution; its current value depends on the assignments that have already run.
  • Use print to inspect a variable's current numeric or string value.
  • Triple quotes preserve line breaks inside a multi-line string.
  • To debug this kind of program, trace each variable after every statement and compare the trace with the displayed output.

Related concepts

More concepts starting with D