Chapter 6
Errors and Debugging
Tracebacks, syntax errors, name errors, type errors, index errors, assertions, invariants, and reduced failing examples.
What this chapter does
Useful Python work depends on reading failures calmly. This chapter teaches errors as evidence: find the failing line, name the broken assumption, inspect the smallest useful value, and reduce the program until the cause is visible.
Lessons
Read these in order.
The chapter opening gives the main idea. Move through these lessons next; each page reuses ideas from the pages before it.
- 01How to Read a Traceback
Error type, message, line number, failing expression, and the bottom-up reading habit.
- 02Syntax Errors
Missing colons, unclosed strings or brackets, indentation, and parse-before-run failures.
- 03Name Errors
Typos, names used before assignment, skipped branches, and local names.
- 04Type Errors
Operations that receive unsuitable value types and how to inspect the mismatch.
- 05Index Errors
Out-of-range sequence indexes, empty lists, and the length-minus-one boundary.
- 06Assertions and Invariants
Stating assumptions directly so failures happen near their cause.
- 07Reducing a Failing Example
Keeping the failure while removing unrelated code until the cause is visible.
You are ready when
- Read the last useful line of a traceback.
- Separate syntax errors from runtime errors.
- Recognize common name, type, and index failures.
- Use assertions to state assumptions.
- Reduce a failing example without changing the failure.
Where this leads
- Files, Paths, and Modules
- Small Objects, Records, and Type Hints
- Small Numerical Experiments