Level 1
0 / 100 XP

Using print to debug

Some bugs don't crash your program — they just give the wrong answer. There's no traceback to read, because nothing technically went wrong. For these, your best tool is the one you already know: print().

The idea: make the invisible visible

When code misbehaves, you're usually guessing about what a variable holds or whether a line even ran. Stop guessing — print it and look.

Python
price = 20 quantity = 3 total = price + quantity # bug: should be * not + print(f"total is {total}") # total is 23 <- not 60, so the math is wrong

That one print instantly shows the total is 23, not the 60 you expected. Now you know the bug is in the calculation, not somewhere else.

Print inside a loop to watch it work

A print inside a loop shows you every step — perfect for catching where a running total or counter goes wrong:

Python
prices = [10, 20, 30] total = 0 for price in prices: print(f"adding {price}, total so far {total}") total = total + price print(f"Final total: {total}")

Output:

Text
adding 10, total so far 0 adding 20, total so far 10 adding 30, total so far 30 Final total: 60

Now you can see the total building up one step at a time. If a number looked wrong, you'd know exactly which step caused it.

Label your prints

A bare print(x) is hard to find in a wall of output. Add a label so you know what you're looking at:

Python
name = "Sam" print("DEBUG name:", name) # DEBUG name: Sam

The word DEBUG and the label make it obvious which print is which — and easy to find and remove later.

A simple debugging routine

  1. Decide what you expect — what should this variable be right now?
  2. Print it at the point you're unsure about.
  3. Compare the printed value to what you expected.
  4. The first place they differ is where your bug lives.
  5. Remove the prints once it's fixed.

Key takeaways

  • Not every bug crashes — some just produce the wrong result, with no traceback
  • **`pr…