Debugging Python
Read error messages and track down the most common Python bugs.
- Read a traceback from the bottom up
- Distinguish NameError, TypeError and IndexError
- Inspect values with print()
- Check assumptions with assert
In plain English
When Python crashes it prints a traceback: a message that shows the error type, a short description and the file and line where it happened. The bottom line of the traceback names the real error, like NameError, TypeError or IndexError. You can add print() calls to see what your variables hold while the program runs. The assert statement checks an assumption and raises an error if it is false.
Step by step
- 1Run the program and read the last line of the traceback to learn the error type.
- 2Open the file and line the traceback points to.
- 3Add print() calls before the crash to inspect the values.
- 4Add assert to make your assumptions explicit and fail early.
def first(items):
assert len(items) > 0
return items[0]
print(first(["python", "sql"]))
print(first([42]))Common mistakes
- Reading the top of a traceback first, which shows other libraries instead of your code.
- Using a variable before it is defined, which raises NameError.
- Adding a string and a number, which raises TypeError.
- Indexing past the end of a list, which raises IndexError.
Fix the crash
The code below crashes. Fix it so it prints the first letter of the word in uppercase.
word = "python"
print(word[6].upper())
Which error happens when you use a variable that has not been defined?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.