To debug Python, read the traceback from the bottom up: the last line names the error, and the lines above show where it happened. Then inspect the values involved, with a quick print(f"{variable=}") or by pausing the program with breakpoint() or the VS Code debugger, until you find where the data stopped being what you expected.

Every programmer writes bugs; good programmers find them quickly. Debugging is a skill you can learn, and it’s mostly about two things: understanding what Python’s error messages are telling you, and looking at your program’s values at the moment things go wrong instead of guessing.

This guide covers how to read a traceback, what the most common errors mean, and three ways to inspect a running program: print debugging, Python’s built-in debugger, and the debugger in VS Code. All the errors and debugger output shown are real. It assumes you know the basics from Python Basics: Functions.

A Buggy Program

Here’s a small script that totals an invoice. One value came from a form, so it arrived as text:

def line_total(item):
    return item["price"] * item["qty"]


def invoice_total(items):
    total = 0
    for item in items:
        total += line_total(item)
    return total


items = [
    {"name": "Website design", "price": 1500, "qty": 1},
    {"name": "Hosting (months)", "price": 25, "qty": "12"},
]
print(invoice_total(items))

Running it crashes:

Traceback (most recent call last):
  File "/home/maria/projects/invoice.py", line 16, in <module>
    print(invoice_total(items))
          ^^^^^^^^^^^^^^^^^^^^
  File "/home/maria/projects/invoice.py", line 8, in invoice_total
    total += line_total(item)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

How to Read a Traceback

A traceback is the list of function calls that were running when the error happened. Read it from the bottom up:

  1. The last line is the error: its type (TypeError) and a message. Here: Python can’t use += to add a string to an integer.
  2. The line above it is where it happened: line 8, total += line_total(item), in the function invoice_total.
  3. Further up are the calls that led there: line 16 called invoice_total(). The ^^^^ markers point to the exact expression on each line.

But notice something: the error appears on line 8, while the real cause is the "12" in the data. Multiplying a number by a string doesn’t fail in Python; it repeats the string, so 25 * "12" quietly produced "121212...". The program only crashed later, when it tried to add that string to a number. Errors often show up after the real mistake, which is why the next step is to look at the values.

Common Errors and What They Mean

These are the errors you’ll see most, with the real messages from Python:

ErrorExample messageUsual cause
SyntaxErrorexpected ':'A typo in the code itself, like a missing colon or bracket. Python finds it before running anything.
NameErrorname 'prnt' is not defined. Did you mean: 'print'?A misspelled name, or a variable used before it’s defined.
TypeErrorcan only concatenate str (not "int") to strMixing types, like text and numbers. Convert with str() or int().
ValueErrorinvalid literal for int() with base 10: '12.5'The type is right but the value isn’t, like int("12.5").
KeyError'Name'A dictionary key that doesn’t exist. Keys are case-sensitive. Use .get() if it might be missing.
IndexErrorlist index out of rangeAsking for item [3] of a three-item list (indexes start at 0).
AttributeError'NoneType' object has no attribute 'upper'Calling a method on the wrong type, often on None returned by a function that forgot to return.
ModuleNotFoundErrorNo module named 'maths'A typo in an import, or a package not installed in the active virtual environment.

Recent Python versions add helpful hints, like “Did you mean: ‘print’?”, so read the whole message before searching online.

Technique 1: Print Debugging With f-Strings

The fastest way to see a value is to print it. Python’s f-strings have a shortcut for this: put = after a variable or expression, and it prints the name and the value:

subtotal = 1500
tax_rate = 0.0775
print(f"{subtotal=} {tax_rate=} {subtotal * tax_rate=}")
subtotal=1500 tax_rate=0.0775 subtotal * tax_rate=116.25

Adding print(f"{item=}") inside the loop of our invoice script would show the 'qty': '12' right away. Print debugging is perfect for quick checks; just remember to remove the prints afterward, or use the logging module for messages you want to keep, as shown in Automate Everyday Tasks With Python.

Technique 2: Pause the Program With breakpoint()

When printing isn’t enough, pause the program and look around. Add breakpoint() where you want to stop:

def invoice_total(items):
    total = 0
    for item in items:
        breakpoint()
        total += line_total(item)
    return total

Run the script as usual. It stops at that line and opens pdb, Python’s built-in debugger, where you can type commands. Here’s a real session:

> /home/maria/projects/invoice_debug.py(9)invoice_total()
-> total += line_total(item)
(Pdb) p item
{'name': 'Website design', 'price': 1500, 'qty': 1}
(Pdb) c
> /home/maria/projects/invoice_debug.py(9)invoice_total()
-> total += line_total(item)
(Pdb) p item
{'name': 'Hosting (months)', 'price': 25, 'qty': '12'}
(Pdb) p type(item["qty"])
<class 'str'>
(Pdb) p line_total(item)
'12121212121212121212121212121212121212121212121212'
(Pdb) q

The first item looks fine, so c continues to the next loop. On the second item, p type(item["qty"]) shows the quantity is a string, and calling line_total(item) reveals the repeated text. Bug found: convert the value with int(item["qty"]), or better, fix it where the data comes in.

The pdb commands you’ll use most:

CommandWhat it does
p expressionPrint a value or expression
pp expressionPretty-print a long dictionary or list
nRun the next line (step over function calls)
sStep into the function on this line
cContinue until the next breakpoint
lShow the code around the current line
wShow where you are (the call stack)
qQuit the program

Remove breakpoint() when you’re done. If you forget one in code that runs on a server, the program will stop and wait for input that never comes.

Technique 3: The VS Code Debugger

Visual Studio Code with Microsoft’s Python extension gives you the same powers with a mouse:

  1. Set a breakpoint: click in the margin to the left of a line number. A red dot appears.
  2. Start debugging: press F5 and choose Python Debugger: Current File.
  3. Inspect: when the program stops, the Variables panel shows every variable’s value. Hover over any variable in the code to see it too.
  4. Step through: use the toolbar to Continue (F5), Step Over (F10), Step Into (F11), or Step Out (Shift+F11).
  5. Watch and evaluate: add expressions like type(item["qty"]) to the Watch panel, or type them in the Debug Console.

Right-click a breakpoint to make it conditional, such as item["name"] == "Hosting (months)", so it only stops on the case you care about, which is a huge time saver in long loops.

A Debugging Process That Works

When something goes wrong:

  1. Read the whole error message, starting from the bottom.
  2. Reproduce it reliably. Find the smallest input that triggers the bug.
  3. Check your assumptions. Look at the actual values with prints or a breakpoint. The bug lives where reality differs from what you expected.
  4. Change one thing at a time, and test after each change.
  5. Explain it out loud. “Rubber duck debugging,” describing the code line by line to someone (or something), often reveals the mistake.
  6. Search the exact error message, minus your own file names and values.
  7. Write a test so the bug can’t come back, as shown in Python Basics: Testing Your Code.

Prevent Bugs Before They Happen

  • Validate input at the edges. Convert and check data where it enters your program (forms, files, APIs), not deep inside calculations.
  • Use type hints and a type checker. Tools like mypy catch many TypeErrors before you run anything; see Python Type Hints.
  • Write small functions. A 10-line function is far easier to debug than a 200-line script.
  • Handle expected errors with try/except, and let unexpected ones show their traceback while you develop.

Frequently Asked Questions

What does “Traceback (most recent call last)” mean?

It’s the header of Python’s error report. It lists the function calls that led to the error, with the most recent call at the bottom, right above the error message.

Is print debugging bad practice?

No. It’s quick and effective for small problems. A debugger is better when you need to explore many values or step through complex logic. Most developers use both.

Why doesn’t my breakpoint stop the program in VS Code?

Usually because you started the program with Run instead of Debug (F5), the line never runs, or VS Code is using a different Python interpreter. Check the interpreter in the bottom-right corner of the window.

How do I debug code that only fails sometimes?

Log the inputs and values with the logging module, so you can see what was different when it failed. Then reproduce that case and use a breakpoint.

Conclusion

Debugging is detective work: read the traceback from the bottom up, form a guess about the cause, and check it by looking at real values, with print(f"{value=}"), a breakpoint() and pdb, or the VS Code debugger. Remember that errors often appear after the real mistake, so follow the data back to where it went wrong. With practice, most bugs go from mysterious to obvious in a few minutes.