Errors and debugging
Debug with small checks and logging
Inspect intermediate values and record useful diagnostic messages.
Lesson 37 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
When output is wrong, reproduce the problem with a small input. Check intermediate values to find where the result first differs from what you expect. Temporary print() calls work for simple scripts; logging provides named severity levels for longer-running programs.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
sessions = [20, 25, 30]
total = 0
for minutes in sessions:
total += minutes
logging.info("Added %s minutes; total is %s", minutes, total)
print(f"Final total: {total}")Final total: 75
INFO: Added 20 minutes; total is 20 INFO: Added 25 minutes; total is 45 INFO: Added 30 minutes; total is 75
By default, logging writes to standard error, so its INFO lines may appear separately from print() output. Log useful values, but avoid putting passwords or other private information in logs.
Pause in the debugger
For a closer look, save the logging example as debugging.py, add breakpoint() immediately before its final print, and run the file from an interactive terminal. At the (Pdb) prompt, type p total to inspect the current value, n to move to the next line, and c to continue. Remove the breakpoint() call after the exercise so later runs do not pause.
Why this works
A small input with a known expected total lets you compare each step. Logging records the current value and the running total as the loop progresses. Python logging writes to standard error by default, so the INFO messages are diagnostic output separate from the final print on standard output.
Practice
Change the last duration to 35. Predict the final total, run the script, and use the INFO messages to inspect each addition. The new total should be 80.
Why inspect an intermediate value?
Reveal answer
It helps locate the first step where the program diverges from the expected result.
Try another case
If the three durations become 20, 25, and 35, what should the final total be?
Check your answer
Reveal answer
It should be 80 minutes; the INFO messages can show how the total reaches that value.
Your progress
Reveal the check answer or reach the end to complete this lesson.