Programming with Python › Python Setup and First Programs › Day 48
Day 48: 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.
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
- 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 - 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 - 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.
- 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:
- Read a Python traceback from the bottom up: identify the exception type and message, then the culprit frame with its file, line number, and function
- Recognize the common built-in exceptions (SyntaxError, IndentationError, NameError, TypeError, ValueError, IndexError, KeyError, AttributeError, ModuleNotFoundError, ZeroDivisionError) and state what each really means
- Distinguish confusable pairs — TypeError vs ValueError, and IndexError vs KeyError — and use the exception type to point at the right fix
- Apply the six-step debugging method: reproduce, read, isolate, hypothesize, test, fix
- Use print-debugging well and pause a running program with breakpoint()/pdb to step through and inspect variables
- Explain why the line named in an error is not always where the bug is, and know when to climb the call stack
- Connect calm, methodical debugging to AI practice, where models, data, and dependencies raise these same exceptions
Prerequisites
- Days 43-47: Python installed, and comfort writing and running small programs with variables, strings, numbers, and input/output
- A terminal and a text editor; no prior debugging experience required
Why this matters
-
You will read far more errors than you write code, and the skill is learnable rather than innate.
-
A traceback names the file, the line and the reason. Most people read only the last line and miss two thirds of it.
-
The error is frequently not where it says. A crash reports where a bad value was used, not where it was made.
-
A systematic method beats intuition, especially when you are tired and it is late.
-
Every framework you use will produce tracebacks through its own code, and finding your line in them is the practical skill.
The idea in plain language
-
A traceback is a stack of frames, printed oldest first and newest last.
-
Read it bottom to top: the last line is the error, the lines above are how you got there.
-
Then read it top to bottom to find the last line that is yours.
-
The exception type tells you the category; the message tells you the specific value.
-
Debugging is a search, and the method is to halve the space rather than to guess.
Historical background
-
Early languages gave you a number. A segmentation fault and an address, and the rest was yours to work out.
-
Structured exceptions arrived to carry context — a type, a message, and the chain of calls that reached the failure.
-
Python’s traceback prints the whole stack rather than only the top, which is more information than most languages of its era offered.
-
Chained exceptions came in Python 3: “During handling of the above exception, another occurred” preserves the original cause rather than losing it.
-
That chaining is why a traceback can be long. Each section is a separate failure, and the first one is usually the real one.
-
The
raise ... from ...form lets you say deliberately which error caused which.
What it is — and what it is not
A traceback is:
- The call stack at the moment the exception was raised, printed in full.
- Ordered oldest to newest, with the failing line last.
- A record of where, not necessarily of why.
It is not:
-
Not necessarily pointing at the bug. It points at where the bad value was used.
-
Not only the last line. The frames above are the context that makes the last line explicable.
-
Not always about your code. Half the frames may be inside a library, and your job is to find the last frame that is yours.
-
Not a failure of the program in every case. An exception can be caught and handled; a traceback means nothing caught it.
Why it was created and what problems it solves
-
Locating a failure. Without a stack, you know only that something broke.
-
Distinguishing categories. A
KeyErrorand aTypeErrorneed entirely different investigations. -
Preserving cause. Chained exceptions keep the original failure when a second one happens during handling.
-
Making libraries debuggable. You can see which of your calls entered the library, and with what.
-
Turning an error into a search. A stack plus a value narrows the space from the whole program to a few lines.
How it works
Reading a traceback, bottom to top
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 last line is the error: type and value.
KeyError: 'amount'means a dictionary was asked for a key it does not have. -
The frame immediately above it is where it happened —
report.py, line 18. -
The frames above that are how you got there, oldest at the top.
-
“Most recent call last” is the header telling you which way to read.
-
Now read downwards for the last line that is yours. In a framework traceback, that line is the one you can actually change.
The common exceptions
| Exception | What it really means |
|---|---|
NameError | The name does not exist — usually a typo or an unimported module |
TypeError | An operation on the wrong kind of thing — often a None where a value was expected |
ValueError | The right type, the wrong value — int("abc") |
KeyError | A dictionary key that is not there |
IndexError | A sequence position that does not exist |
AttributeError | .something on an object that has no such attribute — very often on None |
ImportError | The module is not installed, or not on this path — Day 43 |
FileNotFoundError | The path is wrong, or relative to the wrong directory |
AttributeError: 'NoneType' object has no attribute ...is the most common Python error there is, and it always means the same thing: something returnedNoneand you did not expect it.
The systematic method
- Reproduce it reliably. An intermittent bug is not yet a bug you can fix.
- Read the whole traceback, not the last line.
- Find the last frame that is yours, and look at the values there.
- Form one hypothesis — a specific, checkable statement.
- Test that hypothesis, changing one thing.
- Repeat, halving the space each time.
-
Change one thing at a time. Two changes and a fix tells you nothing about which mattered.
-
Bisect the input as well as the code. Half the rows, and see whether it still fails.
When the error is not where it says
-
A crash reports where a bad value was used, not where it was produced.
-
Noneis the classic case: a function returned it silently, and the error appears three calls later. -
Work backwards from the value, not forwards from the line.
-
Rubber-duck debugging works because explaining forces you to state the assumptions you have not checked.
An everyday analogy
A delivery that arrived damaged.
| The delivery | The traceback |
|---|---|
| The damaged parcel | The exception |
| The last depot that handled it | The final frame |
| The full routing history | The frames above |
| ”Crushed” versus “wet” | The exception type |
| Which depot actually damaged it | The real bug |
| Checking each handover | Bisecting |
-
The last depot reported the damage. It is not necessarily where the damage happened.
-
The routing history is the useful part, and most people read only the label on the front.
-
Working backwards from the damage finds the depot; working forwards from the order does not.
Examples in practice
-
AttributeErroronNonethree functions away from the one that returned it. -
KeyErroron a column that a rename upstream had already changed. -
FileNotFoundErroron a path that exists, because the working directory was not what you assumed — Day 9. -
ImportErrorfor a package you just installed, which is Day 43’s environment mismatch. -
A chained traceback whose second failure is loud and whose first, quieter one is the actual cause.
Implications: security, privacy, performance, scalability, and cost
-
Security: never show a traceback to a user. It reveals file paths, library versions and sometimes values — a map of your system.
-
Log the traceback, show an identifier, so support can find it without the user seeing it.
-
Privacy: exception messages can contain data. A
KeyErrorprints the key; aValueErrormay print the value. Both end up in logs. -
Performance: exceptions are cheap to raise and expensive in a loop. Using them for ordinary control flow over a million items is measurably slow.
-
A bare
except:catches everything, including the interrupt you press to stop the program. Catch specific exceptions. -
Cost: an unhandled exception in a scheduled job is Day 14’s silent failure, unless something is logging and alerting.
Alternatives: free, open source, and commercial
| Tool | Type | What it gives you |
|---|---|---|
traceback module | Free, standard library | Formatting and capturing tracebacks in code |
pdb / breakpoint() | Free, built in | Stop and inspect — Day 37 |
logging.exception | Free, standard library | The traceback, into your log, with context |
rich / better-exceptions | Free, open source | Tracebacks with values shown inline |
pytest --pdb | Free, open source | Drop into the debugger at the failing assertion |
| Sentry and similar | Commercial, free tier | Production tracebacks, grouped and searchable |
-
breakpoint()is built in since Python 3.7. One word, and you are in the debugger at that line. -
logging.exceptioninside anexceptblock records the whole traceback automatically, which is what you want in anything unattended.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Exception | An object describing a failure |
| Traceback | The stack of frames at the moment it was raised |
| Frame | One function call, with its file and line |
| Chained exception | A 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
- Read the whole traceback before changing anything.
- Find the last frame that is yours, and start there.
- Catch specific exceptions, never bare
except:. - Use
logging.exceptionin anything that runs unattended. - Do not show a traceback to a user.
- Do not use exceptions for ordinary control flow in a hot loop.
- Do not fix by guessing. One hypothesis, one change, one test.
The AI connection
-
A training run fails after twenty minutes, and the traceback is the only record of why. Reading it well is the difference between one rerun and five.
-
Shape mismatches are the characteristic AI error, and the traceback names the operation but rarely the reason. The bug is usually a transform several lines earlier.
-
CUDA out of memoryis Day 7’s OOM, arriving from the GPU rather than the kernel — reduce the batch, or the model does not fit. -
The error is often not where it says. A
Nonethat reaches a layer was produced by a loader that quietly returned nothing. -
Reproduce with one small batch on the CPU before debugging anything on a GPU. The traceback is clearer and the loop is seconds rather than minutes.
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 doing | Command |
|---|---|
| Read a full traceback | Run the lab’s failing script |
Provoke a KeyError | {"a": 1}["b"] |
Provoke the None case | A function with no return, then .strip() on the result |
| Find your last frame | In a traceback that passes through a library |
| Stop and look | Add breakpoint() above the failing line |
| Log it properly | logging.exception("failed") inside except |
| Catch specifically | except 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'])
-
The key is
total, notamount— renamed upstream, and the traceback could not have told you that. -
One
pin the debugger answered what reading the code could not.
Validate your work
- You read a traceback bottom to top and then found your last frame
- You can name what each of the eight common exceptions really means
- You debugged a
Noneback to the function that produced it - You used
breakpoint()to inspect a value at the failure - You replaced a bare
except:with a specific one and can say why -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
The traceback is enormous. Most of it is library frames. Search downward for your own filename.
-
Two tracebacks, one after the other. A chained exception. The first is usually the real cause.
-
breakpoint()does nothing.PYTHONBREAKPOINTis set to0, which disables it. -
The error vanishes when you add a print. Usually a timing or ordering issue, and worth taking seriously rather than leaving the print in.
Common mistakes
- Reading only the last line.
- Fixing the line the traceback names, when the bug is upstream.
- Bare
except:. - Changing two things at once.
Practice assignment
-
Collect one real example of each of the eight exceptions and write down, for each, what the message told you and what it did not.
-
Debug a
Nonebug backwards to the function that produced it, without changing any code until you have found it. -
Take a traceback through a library and identify your last frame in under thirty seconds.
-
Convert three bare
except:blocks in code you have written into specific ones, and note what each was hiding.
Extension challenge
-
Write a function that raises with
from, and compare the traceback with the same function raising without it. -
Capture a traceback as a string with the
tracebackmodule and log it, rather than letting it print. -
Reproduce a bug by bisecting the input: halve the dataset repeatedly until you have the smallest input that still fails.
-
Set
sys.excepthookto log unhandled exceptions before the program exits, and confirm a scheduled job now leaves a record rather than silence.
Quiz
Q1. In which order should you read a Python traceback, and why?
- Top to bottom, because the first frame is always where your bug is
- It does not matter; every line says the same thing
- Bottom to top: the last line names the exception
- 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?
- A dictionary key that does not exist
- A sequence index that is out of range
- Code that Python could not parse at all
- 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?
- TypeError is the wrong kind of value; ValueError an unusable one
- They are two names for exactly the same error
- A ValueError only happens with dictionaries; a TypeError only happens with lists
- 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?
- KeyError
- IndexError
- ValueError
- 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?
- Fix, read, reproduce, test, isolate, hypothesize
- Hypothesize, fix, read, reproduce, isolate, test
- Reproduce, read, isolate, hypothesize, test, fix
- 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?
- It permanently deletes the current variable to free memory
- It restarts the program from the first line
- It prints every variable in the program and then exits
- 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"?
- The error surfaces where it failed, not where it was caused
- Because Python reports line numbers at random
- Because tracebacks never include the correct file name
- 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?
- Tracebacks make the program run more slowly for users
- Tracebacks can leak paths, versions, and internal logic
- Users are legally forbidden from reading tracebacks
- 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
- Errors and Exceptions — Python Software Foundation (accessed 2026-07-12)
- Built-in Exceptions — Python Software Foundation (accessed 2026-07-12)
- pdb — The Python Debugger — Python Software Foundation (accessed 2026-07-12)
- Python Traceback — Real Python (accessed 2026-07-12)
- The Missing Semester of Your CS Education — Debugging and Profiling — MIT (accessed 2026-07-12)
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.