Python Foundations·Python from zero

Debugging Python

Read error messages and track down the most common Python bugs.

Beginner 12 min read Lesson 5 of 480 Challenge included
What you will be able to do
  • 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

  1. 1Run the program and read the last line of the traceback to learn the error type.
  2. 2Open the file and line the traceback points to.
  3. 3Add print() calls before the crash to inspect the values.
  4. 4Add assert to make your assumptions explicit and fail early.
debug.pyPython
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.
Your turn

Fix the crash

Easy

The code below crashes. Fix it so it prints the first letter of the word in uppercase.

PYTHON · starter
word = "python"
print(word[6].upper())
Check your understanding before moving on.
Knowledge checkQuestion 1

Which error happens when you use a variable that has not been defined?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Regular expressions
Lesson 5 of 480 · 0% of course