{ Debugging Python. }


By the end of this chapter, you should be able to:

  • Identify common errors in Python
  • Understand the causes of common errors in Python
  • Catch errors using try and except
  • set break points in your Python code

Just like in any programming language we learn, bugs are going to happen! As you've probably noticed, in Python we have quite a few errors. Let's review some of the common ones:


This occurs when a variable is not defined:

# NameError: name 'test' is not defined


This occurs when a dictionary does not have a specific key:

d = {}
# KeyError: 'foo'


This occurs when a variable does not have an attribute:

# AttributeError: 'str' object has no attribute 'foo'


This occurs when you try to access an element in a list using an invalid index (i.e. one that is outside the range of the list):

list = ["hello"]
# IndexError: list index out of range


This occurs when a built-in operation or function receives an argument that has the right type but an inappropriate value:

# ValueError: invalid literal for int() with base 10: 'foo'


This occurs when Python can not interpret two data types:

"awesome" + [] # TypeError: cannot concatenate 'str' and 'list' objects


In python we can also throw errors using the raise keyword. This is helpful when creating your own kinds of exception and error messages.

raise ValueError('invalid value')

try / except

In Python, it is strongly encouraged to use try/except blocks, to catch exceptions when we can do something about them. Let's see what that looks like.

except NameError as err:

We could also write something like this, but you should try not to. Why do you think someone might object to the following code?

    nice + []
    print("Something went wrong!")

What we are doing here is catching every error, which means we are not able to correctly identify "what" went wrong. It is highly discouraged to do this. When you use try/except, make sure that a specific type of exception is being handled. If you want to except a handful of exceptions, you can pass a tuple of errors into the except block as well:

    # do some stuff
except (NameError, ValueError) as e:
    # do some other stuff

Debugging with pdb

To set breakpoints in our code we can use pdb by inserting this line:

import pdb; pdb.set_trace() 

Inside of the debugger we can press c to continue and q to quit. There are a few more shortcuts as well; you can read more about pdb here.

When you're ready, move on to Modules Introduction