Python course · Module 7: Files and errors · Lesson 37 of 63
Quick answer: To debug, read the traceback from the bottom up, then put breakpoint() where you want to stop. Python opens the pdb debugger there: p name prints a variable, n runs the next line, s steps into a function, c continues and q quits. For messages from a running program, use Python logging instead of print(): logging.basicConfig(level=logging.INFO), then logging.info("Order saved"). Every log message gets a level and a source, and logs can go to a file.
In this lesson you will learn:
- how to read a traceback, and when print debugging is enough
- how to stop a program with
breakpoint()and use the pdb commandsn,s,c,p,landq - how to switch all breakpoints off with
PYTHONBREAKPOINT=0 - the five logging levels,
basicConfig(), message formats and logging to a file getLogger(__name__),logging.exception()and why real programs log instead of print
Before you start: finish Lesson 36, Python raise and Custom Exceptions. You need try/except from Lesson 35 and reading files from Lesson 32. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, except for the times in the log lines.
Table of Contents
Read a traceback from the bottom up
Our running example adds up a shopping cart with discounts. It crashes:
def apply_discount(price, percent):
return price - percent / 100
def cart_total(cart, discounts):
total = 0
for item, price in cart.items():
total += apply_discount(price, discounts[item])
return total
cart = {"pen": 1.5, "notebook": 3.0, "bag": 20.0}
discounts = {"pen": 0, "notebook": 10}
print("Total:", cart_total(cart, discounts))
Traceback (most recent call last):
File "/home/learner/python-course/w36/step1_traceback.py", line 14, in <module>
print("Total:", cart_total(cart, discounts))
~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/home/learner/python-course/w36/step1_traceback.py", line 8, in cart_total
total += apply_discount(price, discounts[item])
~~~~~~~~~^^^^^^
KeyError: 'bag'
Read a traceback from the bottom up:
- The last line is the error type and message:
KeyError: 'bag'. Some key was missing in a dictionary. - The lines just above it show where it happened: line 8, inside
cart_total(), and the~~~^^^marks point atdiscounts[item]. - The higher blocks show how the program got there: line 14 called
cart_total(). The newest call is at the bottom.
So discounts has no "bag" key. A missing discount should mean 0 %, so we use discounts.get(item, 0) (Lesson 17).
Print debugging
The crash is gone, but now the answer is wrong. With 10 % off the notebook, the total should be 1.5 + 2.7 + 20.0 = 24.2:
def apply_discount(price, percent):
return price - percent / 100
def cart_total(cart, discounts):
total = 0
for item, price in cart.items():
total += apply_discount(price, discounts.get(item, 0))
return total
cart = {"pen": 1.5, "notebook": 3.0, "bag": 20.0}
discounts = {"pen": 0, "notebook": 10}
print("Total:", cart_total(cart, discounts))
print("Expected: 24.2")
Total: 24.4
Expected: 24.2
There is no traceback, so we must look inside. The quickest way is a temporary print() in the loop:
for item, price in cart.items():
new_price = apply_discount(price, discounts.get(item, 0))
print("DEBUG:", item, price, discounts.get(item, 0), new_price)
total += new_price
DEBUG: pen 1.5 0 1.5
DEBUG: notebook 3.0 10 2.9
DEBUG: bag 20.0 0 20.0
Total: 24.4
The notebook costs 3.0 with 10 % off, but the new price is 2.9, not 2.7. The bug is in apply_discount(). Print debugging is fine for a quick look, but you must guess what to print and delete the prints afterwards.
Debug with breakpoint() and pdb
A debugger stops your program while it runs, so you can look at any variable and move one line at a time. Python’s debugger is pdb. The pdb docs say the typical way to start it is to put breakpoint() where you want to stop, and then run the program as usual. We replace the print() with breakpoint():
for item, price in cart.items():
breakpoint()
total += apply_discount(price, discounts.get(item, 0))
Here is the real session in a terminal. The text after each (Pdb) prompt is what we typed:
$ python3 step4_breakpoint.py
> /home/learner/python-course/w36/step4_breakpoint.py(8)cart_total()
-> breakpoint()
(Pdb) l
3
4
5 def cart_total(cart, discounts):
6 total = 0
7 for item, price in cart.items():
8 -> breakpoint()
9 total += apply_discount(price, discounts.get(item, 0))
10 return total
11
12
13 cart = {"pen": 1.5, "notebook": 3.0, "bag": 20.0}
(Pdb) p item, price
('pen', 1.5)
(Pdb) c
> /home/learner/python-course/w36/step4_breakpoint.py(8)cart_total()
-> breakpoint()
(Pdb) p item, price, total
('notebook', 3.0, 1.5)
(Pdb) n
> /home/learner/python-course/w36/step4_breakpoint.py(9)cart_total()
-> total += apply_discount(price, discounts.get(item, 0))
(Pdb) s
--Call--
> /home/learner/python-course/w36/step4_breakpoint.py(1)apply_discount()
-> def apply_discount(price, percent):
(Pdb) n
> /home/learner/python-course/w36/step4_breakpoint.py(2)apply_discount()
-> return price - percent / 100
(Pdb) p price, percent
(3.0, 10)
(Pdb) p price - percent / 100
2.9
(Pdb) p price - price * percent / 100
2.7
(Pdb) q
Quitting pdb will kill the process. Quit anyway? [y/n] y
Step by step:
- The program stopped at line 8.
->shows the line that runs next. l(list) printed the code around the current line.p item, priceprinted the values for the first item, the pen.c(continue) ran untilbreakpoint()was reached again, in the second round: the notebook, with a total of 1.5 so far.n(next) ran one line.s(step) went into theapply_discount()call (--Call--), andnmoved to itsreturnline.p price - percent / 100gave the wrong 2.9.p price - price * percent / 100tested a fix: 2.7. The function forgets to multiply byprice.q(quit) asked for confirmation. Since Python 3.14, the pdb docs say, quitting shows “a confirmation prompt” when pdb was started bybreakpoint().yended the program.
| Command | Meaning |
|---|---|
n (next) | run the current line and stop at the next line in this function |
s (step) | like n, but go into a function that the line calls |
c (continue) | run until the next breakpoint |
p expression | print the value of a variable or expression |
l (list) | show the code around the current line |
q (quit) | stop debugging and end the program |
The docs explain the difference: s “stops inside a called function”, while n runs called functions “at (nearly) full speed”.
Turn breakpoints off with PYTHONBREAKPOINT=0
A forgotten breakpoint() stops the program for every user. The sys docs say that if the environment variable PYTHONBREAKPOINT is set to "0", breakpoint() does nothing:
$ PYTHONBREAKPOINT=0 python3 step4_breakpoint.py
Total: 24.4
The program ran straight to the end. On Windows, set the environment variable PYTHONBREAKPOINT to 0 in your terminal first. This is only a safety net; remove breakpoint() lines before you share your code.
Why use Python logging instead of print?
The Logging HOWTO recommends print() to “display console output for ordinary usage”, and logging to “report events that occur during normal operation of a program”. Log messages have three advantages:
- Each message has a level, so you can hide the less important ones without deleting code.
- Each message can show the time and the module it came from.
- Messages can go to a file, so you can read them after a crash.
Python logging levels
The logging module has five levels, from least to most serious:
import logging
logging.debug("Cart has 3 items")
logging.info("Order 1001 saved")
logging.warning("Only 2 notebooks left")
logging.error("Payment failed for order 1002")
logging.critical("Database is not reachable")
print("Level numbers:", logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
WARNING:root:Only 2 notebooks left
ERROR:root:Payment failed for order 1002
CRITICAL:root:Database is not reachable
Level numbers: 10 20 30 40 50

Only three messages appeared. The HOWTO explains: “The default level is WARNING“, so debug() and info() are dropped. Each level is a number (10 to 50), and a message is shown when its number is at least the chosen level. root is the name of the default logger. Use DEBUG for details, INFO for normal events, WARNING for something unexpected, ERROR when a task failed, and CRITICAL when the program may not continue.
Configure logging with basicConfig()
logging.basicConfig() sets the level and the layout of the messages. Call it once, at the start of your program:
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
item, quantity = "notebook", 5
logging.debug("Cart has 3 items")
logging.info("Sold %s %s", quantity, item)
logging.warning("Only %d %s left", 2, item)
2026-11-08 14:47:13,197 DEBUG root: Cart has 3 items
2026-11-08 14:47:13,197 INFO root: Sold 5 notebook
2026-11-08 14:47:13,197 WARNING root: Only 2 notebook left
level=logging.DEBUGshows every level.formatis a template:%(asctime)sis the date and time,%(levelname)sthe level,%(name)sthe logger name and%(message)syour text.logging.info("Sold %s %s", quantity, item)passes the values separately. The HOWTO says logging uses the old%sstyle for this, and “formatting of message arguments is deferred until it cannot be avoided”, so a hidden message is never built into text.
Log to a file
Add filename= and the messages go to a file instead of the screen:
import logging
logging.basicConfig(
filename="shop.log",
filemode="w",
encoding="utf-8",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logging.info("Shop started")
logging.warning("Only 2 notebooks left")
print("Nothing on the screen from logging. Now the file:")
with open("shop.log", encoding="utf-8") as f:
print(f.read(), end="")
Nothing on the screen from logging. Now the file:
2026-11-08 14:47:13 INFO Shop started
2026-11-08 14:47:13 WARNING Only 2 notebooks left
The logging docs say filemode defaults to 'a' (append), so each run adds to the file; "w" starts a new file every run. encoding="utf-8" works as in Lesson 32, and datefmt sets the time format (ours has no milliseconds).
Use getLogger(__name__) in every module
In a real program, each module makes its own logger. The HOWTO calls this “a good convention”: logger = logging.getLogger(__name__). Since __name__ is the module name (Lesson 28), every message shows where it came from. Here is a module cart.py:
import logging
logger = logging.getLogger(__name__)
def cart_total(cart):
logger.debug("Adding up %d items", len(cart))
total = sum(cart.values())
logger.info("Cart total is %.2f", total)
return total
And the main program app.py in the same folder. Only the main program calls basicConfig():
import logging
import cart
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger.info("App started")
cart.cart_total({"pen": 1.5, "notebook": 3.0})
logging.getLogger("cart").setLevel(logging.DEBUG)
cart.cart_total({"bag": 20.0})
INFO __main__: App started
INFO cart: Cart total is 4.50
DEBUG cart: Adding up 1 items
INFO cart: Cart total is 20.00
- Messages from
app.pyshow__main__, and messages fromcart.pyshowcart.%.2fmeans two decimals. - The first
debug()incartwas hidden by theINFOlevel.setLevel(logging.DEBUG)on thecartlogger turned on debug messages for that one module only. - The docs say all calls with the same name “return the same logger instance”, so you never pass loggers around.
Log errors with logging.exception()
Inside an except block, logger.exception() logs an ERROR message and the full traceback, and the program keeps running:
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
orders = ["2", "ten", "4"]
for text in orders:
try:
quantity = int(text)
except ValueError:
logger.exception("Could not read quantity %r", text)
continue
logger.info("Quantity %d accepted", quantity)
INFO __main__: Quantity 2 accepted
ERROR __main__: Could not read quantity 'ten'
Traceback (most recent call last):
File "/home/learner/python-course/w36/step9_exception.py", line 9, in <module>
quantity = int(text)
ValueError: invalid literal for int() with base 10: 'ten'
INFO __main__: Quantity 4 accepted
%r shows the value with its quotes. The docs say this method “should only be called from an exception handler”, which means inside except.
Try it yourself
Exercise 1: Log the orders
Set logging to INFO with the format "%(levelname)s: %(message)s". For each order in [("pen", 4), ("notebook", 5)] with stock = {"pen": 10, "notebook": 2}, log an INFO message when you sell it and a WARNING when there is not enough stock.
Exercise 2: Debug messages in a file
Log to orders.log (new file each run, UTF-8, level DEBUG, format "%(levelname)s %(name)s: %(message)s") with a logger from getLogger(__name__). For the quantities 3 and 0, log a DEBUG message, and an ERROR for 0. Print the file at the end.
Exercise 3: Find the bug with pdb
This function should print 6.0, but prints 2.0. Put breakpoint() before the return line and inspect the variables with p:
def average(numbers):
for n in numbers:
total = 0
total += n
return total / len(numbers)
print(average([4, 8, 6]))
Solutions
Solution 1
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
stock = {"pen": 10, "notebook": 2}
orders = [("pen", 4), ("notebook", 5)]
for item, quantity in orders:
if quantity > stock[item]:
logging.warning("Order for %d %s, but only %d in stock", quantity, item, stock[item])
else:
stock[item] -= quantity
logging.info("Sold %d %s, %d left", quantity, item, stock[item])
INFO: Sold 4 pen, 6 left
WARNING: Order for 5 notebook, but only 2 in stock
%d puts whole numbers into the message, just like %s.
Solution 2
import logging
logging.basicConfig(
filename="orders.log",
filemode="w",
encoding="utf-8",
level=logging.DEBUG,
format="%(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
for quantity in [3, 0]:
logger.debug("Checking quantity %d", quantity)
if quantity == 0:
logger.error("Quantity must be at least 1")
with open("orders.log", encoding="utf-8") as f:
print(f.read(), end="")
DEBUG __main__: Checking quantity 3
DEBUG __main__: Checking quantity 0
ERROR __main__: Quantity must be at least 1
Nothing appeared on the screen until we printed the file.
Solution 3
$ python3 solution3_average_bug.py
> /home/learner/python-course/w36/solution3_average_bug.py(5)average()
-> breakpoint()
(Pdb) p numbers
[4, 8, 6]
(Pdb) p total
6
(Pdb) p sum(numbers)
18
(Pdb) c
2.0
total is 6, only the last number. total = 0 is inside the loop, so it is reset every round. Move it above the loop:
def average(numbers):
total = 0
for n in numbers:
total += n
return total / len(numbers)
print(average([4, 8, 6]))
6.0
Common mistakes
- Expecting
logging.info()to show without setup. The default level isWARNING, sologging.info("Order 1001 saved")printed nothing in our test. Calllogging.basicConfig(level=logging.INFO)first. - Calling
basicConfig()after the first log message. A firstlogging.warning()sets up logging with the defaults, and the docs saybasicConfig()then “does nothing”. Our laterlevel=logging.DEBUGwas ignored: the info message was lost and the oldWARNING:root:format stayed. Call it first, or passforce=True. - Using
logging.exception()outsideexcept. There is no error to show, and our test printedNoneType: Noneunder the message. - Naming your own file
logging.py. Thenimport logging(Lesson 27) imports your file, and Python 3.14 says:AttributeError: module 'logging' has no attribute 'basicConfig' (consider renaming ... since it has the same name as the standard library module named 'logging' ...). Rename the file. - Leaving
breakpoint()in finished code. The program stops and waits at a(Pdb)prompt. Remove it, or run withPYTHONBREAKPOINT=0.
Frequently asked questions
What is the difference between print and logging in Python?
print() writes output the user should see. Logging adds a level, time and source to every message, can hide the less important ones, and can write to a file. Use logging for messages about what the program is doing.
How do I use breakpoint() in Python?
Put breakpoint() on its own line where you want to stop and run the program normally. Python stops there with a (Pdb) prompt. It is built in since Python 3.7, so you need no import.
How do I write Python logs to a file?
Call logging.basicConfig(filename="app.log", encoding="utf-8", level=logging.INFO) at the start of the program. Add filemode="w" if each run should start a new file; the default "a" appends.
Summary
- Read a traceback from the bottom: the last line is the error, the frame above it is where it happened.
print()is fine for a quick look;breakpoint()stops the program in pdb, wherel,p,n,s,candqlet you inspect and move line by line.PYTHONBREAKPOINT=0makes everybreakpoint()do nothing.- Logging has five levels (
DEBUGtoCRITICAL, defaultWARNING);basicConfig()sets the level, the format and an optional log file. - Use
logger = logging.getLogger(__name__)in each module,%sarguments in messages, andlogger.exception()insideexceptto keep the traceback.
Next lesson
Next: Lesson 38, Python Classes and Objects: A Beginner’s Guide.
Sources
- pdb: The Python Debugger (Python docs)
- breakpoint() (Python built-in functions)
- sys.breakpointhook and PYTHONBREAKPOINT (Python docs)
- Logging HOWTO (Python docs)
- logging: Logging facility for Python (Python docs)
- Python downloads page (python.org)





