Programming with Python › Python Setup and First Programs › Day 48

Day 48: Reading Error Messages and Debugging

Day 48 of 365 — Reading Error Messages and Debugging

After this lesson you will be able to read any Python traceback bottom-up, recognize the common exceptions on sight, and work through a bug with a calm, repeatable method instead of guessing.

Course
Programming with Python
Category
Python Setup and First Programs
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-048-reading-error-messages-and-debugging

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/programming-with-python/day-048-reading-error-messages-and-debugging
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: how to read a traceback in two passes


Historical background


What it is — and what it is not

A traceback is:

It is not:


Why it was created and what problems it solves


How it works

Reading a traceback, bottom to top

Diagram: how chained exceptions are printed and which one matters

Diagram: the anatomy of a Python traceback, read from the bottom up

Traceback (most recent call last):
  File "run.py", line 42, in <module>
    main()
  File "run.py", line 31, in main
    total = summarise(rows)
  File "report.py", line 18, in summarise
    return sum(r["amount"] for r in rows)
KeyError: 'amount'

The common exceptions

Diagram: what each common Python exception category indicates

ExceptionWhat it really means
NameErrorThe name does not exist — usually a typo or an unimported module
TypeErrorAn operation on the wrong kind of thing — often a None where a value was expected
ValueErrorThe right type, the wrong value — int("abc")
KeyErrorA dictionary key that is not there
IndexErrorA sequence position that does not exist
AttributeError.something on an object that has no such attribute — very often on None
ImportErrorThe module is not installed, or not on this path — Day 43
FileNotFoundErrorThe path is wrong, or relative to the wrong directory

The systematic method

Diagram: the loop of forming and testing a single hypothesis

Flowchart: the debugging method loop from reproduce to fix

  1. Reproduce it reliably. An intermittent bug is not yet a bug you can fix.
  2. Read the whole traceback, not the last line.
  3. Find the last frame that is yours, and look at the values there.
  4. Form one hypothesis — a specific, checkable statement.
  5. Test that hypothesis, changing one thing.
  6. Repeat, halving the space each time.

When the error is not where it says

Diagram: where an error is reported compared with where it was caused


An everyday analogy

A delivery that arrived damaged.

The deliveryThe traceback
The damaged parcelThe exception
The last depot that handled itThe final frame
The full routing historyThe frames above
”Crushed” versus “wet”The exception type
Which depot actually damaged itThe real bug
Checking each handoverBisecting

Examples in practice

Diagram: narrowing a failure by halving the input data


Implications: security, privacy, performance, scalability, and cost

Diagram: a bare except clause compared with a specific one


Alternatives: free, open source, and commercial

Diagram: showing a traceback to a user compared with logging it

ToolTypeWhat it gives you
traceback moduleFree, standard libraryFormatting and capturing tracebacks in code
pdb / breakpoint()Free, built inStop and inspect — Day 37
logging.exceptionFree, standard libraryThe traceback, into your log, with context
rich / better-exceptionsFree, open sourceTracebacks with values shown inline
pytest --pdbFree, open sourceDrop into the debugger at the failing assertion
Sentry and similarCommercial, free tierProduction tracebacks, grouped and searchable

TermWhat it actually is
ExceptionAn object describing a failure
TracebackThe stack of frames at the moment it was raised
FrameOne function call, with its file and line
Chained exceptionA second failure during the handling of a first
raise ... from ...Stating the cause deliberately
Bare except:Catching everything, including what you should not

When to use it — and when not to

Diagram: debugging an intermittent failure compared with a reproducible one


The AI connection

Knowledge check

quiz:
  question: "A traceback ends with `AttributeError: 'NoneType' object has no attribute 'strip'` on a line that calls `value.strip()`. Where is the bug most likely to be?"
  options:
    - "Wherever value was produced, since something returned None and the failing line merely used it"
    - "On the failing line, which should call strip() on a different attribute"
    - "In the strip method, which does not handle a None receiver"
    - "In the frame at the top of the traceback, which is the oldest call"
  answer_index: 0
  explanation: "The traceback reports where the bad value was used, not where it was made. A function returned None — often by falling off the end without an explicit return — and the failure surfaces at the first line that treats it as a string, which may be several calls away."

Hands-on exercise

Provoke each common exception, then debug one systematically. Worked through fully in the Day 48 lab directory.

What you are doingCommand
Read a full tracebackRun the lab’s failing script
Provoke a KeyError{"a": 1}["b"]
Provoke the None caseA function with no return, then .strip() on the result
Find your last frameIn a traceback that passes through a library
Stop and lookAdd breakpoint() above the failing line
Log it properlylogging.exception("failed") inside except
Catch specificallyexcept KeyError: rather than bare except:

Expected output

  File "report.py", line 18, in summarise
    return sum(r["amount"] for r in rows)
KeyError: 'amount'
> /project/report.py(18)summarise()
(Pdb) p rows[0].keys()
dict_keys(['id', 'total'])

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. In which order should you read a Python traceback, and why?

  1. Top to bottom, because the first frame is always where your bug is
  2. It does not matter; every line says the same thing
  3. Bottom to top: the last line names the exception
  4. Only the middle frames matter; ignore the top and bottom
Show answer

Answer: C. Bottom to top: the last line names the exception

Tracebacks list calls oldest-first, so the most recent call sits at the bottom next to the exception. Reading bottom-up gives you the "what" (the exception type and message) and then the "where" (the nearest frame) with the least wasted effort.

Q2. A program raises TypeError. What category of mistake does that signal?

  1. A dictionary key that does not exist
  2. A sequence index that is out of range
  3. Code that Python could not parse at all
  4. An operation given a value of the wrong type
Show answer

Answer: D. An operation given a value of the wrong type

A TypeError means an operation received the wrong KIND of value — for example "3" + 5, where no value would make string-plus-integer valid. That differs from a ValueError, where the type is right but the specific value is unacceptable.

Q3. What is the difference between a TypeError and a ValueError?

  1. TypeError is the wrong kind of value; ValueError an unusable one
  2. They are two names for exactly the same error
  3. A ValueError only happens with dictionaries; a TypeError only happens with lists
  4. A TypeError happens before the program starts; a ValueError happens while it runs
Show answer

Answer: A. TypeError is the wrong kind of value; ValueError an unusable one

int("hello") raises ValueError because a string is the right type for int() but "hello" is not a number. "3" + 5 raises TypeError because a string and an integer are incompatible kinds for the + operation.

Q4. You look up my_list[5] on a list that has three items. Which exception is raised?

  1. KeyError
  2. IndexError
  3. ValueError
  4. AttributeError
Show answer

Answer: B. IndexError

IndexError means a sequence index is out of range. A three-item list has valid positions 0, 1, and 2, so asking for position 5 walks off the end. A missing lookup in a dictionary would instead raise KeyError.

Q5. What is the correct order of the six-step systematic debugging method?

  1. Fix, read, reproduce, test, isolate, hypothesize
  2. Hypothesize, fix, read, reproduce, isolate, test
  3. Reproduce, read, isolate, hypothesize, test, fix
  4. Read, fix, reproduce, hypothesize, isolate, test
Show answer

Answer: C. Reproduce, read, isolate, hypothesize, test, fix

First make the failure reproducible, then read the error, isolate the smallest failing piece, form one testable hypothesis about the cause, test it, and only then fix the cause — re-running your reproduction to confirm.

Q6. What does the built-in breakpoint() function do when your program reaches it?

  1. It permanently deletes the current variable to free memory
  2. It restarts the program from the first line
  3. It prints every variable in the program and then exits
  4. It pauses the program and drops you into the debugger
Show answer

Answer: D. It pauses the program and drops you into the debugger

breakpoint() (added in Python 3.7) stops execution at that line and opens the pdb debugger prompt, where commands like p (print a value), n (next line), s (step into), and c (continue) let you inspect the live program without adding and re-running print statements.

Q7. Why is it said that "where the program broke is not always where it went wrong"?

  1. The error surfaces where it failed, not where it was caused
  2. Because Python reports line numbers at random
  3. Because tracebacks never include the correct file name
  4. Because every exception is actually a SyntaxError in disguise
Show answer

Answer: A. The error surfaces where it failed, not where it was caused

A ZeroDivisionError on total / len(values) is genuine, but the actual mistake may be far earlier where values was filled from an empty file. The call stack exists precisely so you can climb from the symptom to a cause hiding in a caller.

Q8. Why should you avoid showing raw tracebacks to the users of a program you build?

  1. Tracebacks make the program run more slowly for users
  2. Tracebacks can leak paths, versions, and internal logic
  3. Users are legally forbidden from reading tracebacks
  4. Tracebacks only display correctly for the original author
Show answer

Answer: B. Tracebacks can leak paths, versions, and internal logic

A raw traceback can reveal file paths, function names, library versions, and even the offending data — a useful map for an attacker. Detailed tracebacks belong in your private console and logs; users should see a calm generic message instead.

Glossary

exception
A signal Python raises when it cannot carry out an instruction; it has a type that categorizes the problem and usually a message with the specifics, and it stops normal execution unless the program catches it.
traceback
The report Python prints when an uncaught exception occurs, showing the chain of function calls that led to the failure, each with its file, line number, and code, ending with the exception type and message.
stack frame
One entry in a traceback (and in the call stack): a single function's place in the chain of calls, recording the file, line number, function name, and the exact line being executed.
call stack
The ordered chain of function calls active at a given moment — who called whom — which the traceback lists oldest-first so the most recent call sits nearest the error.
SyntaxError
An error raised when Python cannot parse your code because it is not valid Python; it stops the program from starting at all.
IndentationError
A special kind of SyntaxError caused by wrong or inconsistent indentation, such as a line indented where Python did not expect it.
NameError
An error raised when you use a name that does not exist, usually because of a typo or because the name was used before it was defined.
TypeError
An error raised when an operation receives a value of the wrong type, such as trying to add a string to an integer.
ValueError
An error raised when a value is the right type but unacceptable for the operation, such as calling int("hello").
IndexError
An error raised when you access a position in an ordered sequence (a list or tuple) that is out of range.
KeyError
An error raised when you look up a key in a dictionary that does not exist.
AttributeError
An error raised when you access an attribute or method that an object does not have, often due to a typo in the method name.
ModuleNotFoundError
An error raised when Python cannot find a module you tried to import, commonly because it is not installed in the current environment.
pdb
Python's built-in interactive debugger, which lets you pause a running program at a prompt and inspect variables, step line by line, and continue.
breakpoint
A built-in function (added in Python 3.7) that pauses the program where it is called and drops you into the pdb debugger, replacing the older import pdb; pdb.set_trace() incantation.
print-debugging
The practice of adding temporary print() calls to reveal a program's values and control flow; fast for a quick, specific question but requires editing and re-running.
rubber-duck debugging
The practice of explaining your code aloud, line by line, to an inanimate object or patient listener, which often surfaces the flaw the moment intent and reality are compared.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.