Tutorials Logic, IN info@tutorialslogic.com

Python Debugging: Read Errors, Inspect Values, and Fix Bugs

Python Debugging

Debugging means finding the difference between what the code does and what you expected it to do.

Good debugging starts with the exact error message, the line number, and the smallest input that reproduces the problem.

Use prints, assertions, and breakpoints to inspect values before changing code blindly.

Traceback Reading

A traceback shows the call path that led to the error. The most useful line is usually the last frame that points to your own file.

  • Read from the bottom upward.
  • Find the file and line number in your code.
  • Fix the cause, not only the final symptom.

Isolate a Bad Value

Isolate a Bad Value
prices = ["10", "20", "free"]

for price in prices:
    print("checking:", price)
    print(int(price))
Output
checking: 10
10
checking: 20
20
checking: free
ValueError: invalid literal for int() with base 10: 'free'

The print before conversion shows which value causes the failure.

Breakpoints

breakpoint() pauses the program so you can inspect variables step by step in the debugger.

  • Place the breakpoint before the suspicious line.
  • Inspect current variable values.
  • Remove breakpoints before final cleanup.

Pause Before a Calculation

Pause Before a Calculation
quantity = 3
price = "25"

breakpoint()
total = quantity * int(price)
print(total)

When run locally, breakpoint() opens the debugger before total is calculated.

Before you move on

Can You Use Python Debugging?

5 checks
  • You can identify the user-code line in a traceback.
  • You can reproduce a bug with a small input.
  • You can inspect values before the failing line.
  • You can use breakpoint() for local debugging.
  • You can explain the bug before applying a fix.

Debugging Decisions

0 of 2 checked

Q1. Where should you usually start reading a traceback?

Q2. What makes a bug easier to fix?

Debugging Habits That Mislead

  • Changing too many lines

    Change one cause at a time and rerun the smallest reproduction.
  • Ignoring the first bad value

    Print or inspect inputs near the failing line before rewriting logic.
  • Catching every exception

    Do not hide the traceback while learning. Catch only expected problems.

Try this next

Debug a Broken Script

0 of 3 completed

  1. Create a list with one invalid number string and print the value before int().
  2. Add assert total >= 0 before returning a calculated total.
  3. Copy a small error and mark the exact file line you should inspect first.

Questions About Python Debugging

No. Small print checks are useful. Remove or replace them with logging when the code becomes a real program.

Use it when you need to inspect several variables or step through code locally.

Start from the last frame that points to your code, then use earlier frames only if the cause is not obvious.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.