Debugging in Python: read the error messages!

If your code produces an error, always look at the error message that python gives you! Error messages will tell which line of code that caused the error and the type of error that occurred, usually with some helpful statement.

For example, here is some code which raises an error:

In [1]:
for i in range(5):
    print w
NameError                                 Traceback (most recent call last)
<ipython-input-1-70e2694c9d34> in <module>()
      1 for i in range(5):
----> 2     print w

NameError: name 'w' is not defined

In this error output, we see an arrow pointing to the "broken" line of code (line 2). This helps us direct our debugging efforts, because we know exactly where the problematic code is located. Sometimes, you will instead see an explicit line number printed out telling you where the error is (see examples below).

In addition, the output tells us that a NameError occurred. In python, a NameError occurs when you attempt to use a variable that does not exist. This is exactly what python told us: "NameError: name 'w' is not defined". This error message tells us plainly that the variable w does not exist. So, we know we should modify our code so that there is a w to print!

In [2]:
w = 82
for i in range(5):
    print w    

And now, the code works properly with no errors. There are many other types of "standard errors" like NameError (see here:, but here are some ones you'll likely encounter:

  • SyntaxError
  • IndentationError
  • ValueError
  • TypeError
  • KeyError
  • IndexError

Examples of these errors are shown below.

Syntax Error

A SyntaxError occurs when you have not written a piece of code properly. These errors generally indicate that you have a typo, and they often happen when you are missing important symbols.

Python tells you exactly where the syntax problem is by explicitly stating the line in which the error occurred. Also, python actually gives a little carrot arrow to point out the exact location in the line where it found a syntax issue!

In [3]:
# SyntaxError example 1
# Missing a closing bracket at the end of list definition

mylist = [1,2,3,4   
  File "<ipython-input-3-e6173cc81587>", line 4
    mylist = [1,2,3,4
SyntaxError: invalid syntax
In [4]:
# SyntaxError example 2 - 
# To print two values together, you need to separate them with a comma (or for strings, a plus sign)

a = "string 1"
b = "string 2"
print a b
  File "<ipython-input-4-18b5d8145697>", line 6
    print a b
SyntaxError: invalid syntax
In [5]:
# SyntaxError example 3
# missing colon when writing a for loop

fruit = ["banana", "apple", "pear", "grape"]
for f in fruit
    print "This is a fruit:", f
  File "<ipython-input-5-95c90e82bf39>", line 5
    for f in fruit
SyntaxError: invalid syntax


An IndentationError occurs when you have either inconsistent or improper indentation (i.e. the required white-space in the beginning of if statements, for loops, and functions).

In [6]:
# IndentationError example
if 7 > 9:
print "7 is greater than 9"
  File "<ipython-input-6-83175296cffd>", line 3
    print "7 is greater than 9"
IndentationError: expected an indented block
In [7]:
# IndentationError example. This time, indents are inconsistent across the code
for i in range(10):
    print "here is the value of i:"
     print i
  File "<ipython-input-7-3503049c88f1>", line 4
    print i
IndentationError: unexpected indent


A ValueError occurs when you provide a python function with an inappropriate argument.

In [8]:
# ValueError example
number = "mystring!"
print int(number)
ValueError                                Traceback (most recent call last)
<ipython-input-8-a899aa91003e> in <module>()
      1 # ValueError example
      2 number = "mystring!"
----> 3 print int(number)

ValueError: invalid literal for int() with base 10: 'mystring!'


A TypeError occurs when you apply an operation to a variable of inappropriate type. They are similar to ValueErrors, although TypeErrors happen specifically when the operation being used only works on certain variable types. For instance, the len() function is only allowed to be used on lists, dictionaries, strings, and tuples.

In [9]:
# TypeError example 1
a = 7
print len(a)
TypeError                                 Traceback (most recent call last)
<ipython-input-9-b2aff0ba5352> in <module>()
      1 # TypeError example 1
      2 a = 7
----> 3 print len(a)

TypeError: object of type 'int' has no len()
In [10]:
# TypeError example 2 - you can't subtract from strings!
a = "this is a string"
print a - 1 
TypeError                                 Traceback (most recent call last)
<ipython-input-10-e9fef33b82fc> in <module>()
      1 # TypeError example 2 - you can't subtract from strings!
      2 a = "this is a string"
----> 3 print a - 1

TypeError: unsupported operand type(s) for -: 'str' and 'int'


A KeyError occurs when you attempt to index a key in a dictionary, but that key does not exist.

In [11]:
# KeyError example
d = {"seven": 7, "nine": 9, "eleven": 11}
print d["five"]
KeyError                                  Traceback (most recent call last)
<ipython-input-11-628e9b0396a6> in <module>()
      1 # KeyError example
      2 d = {"seven": 7, "nine": 9, "eleven": 11}
----> 3 print d["five"]

KeyError: 'five'


An IndexError occurs when you attempt to index a position from a list or string, but that index isn't in the variable.

In [12]:
# IndexError example 1
mylist = [11, 22, 33, 44, 55, 66]
print mylist[9]
IndexError                                Traceback (most recent call last)
<ipython-input-12-e895b208c4db> in <module>()
      1 # IndexError example 1
      2 mylist = [11, 22, 33, 44, 55, 66]
----> 3 print mylist[9]

IndexError: list index out of range
In [13]:
# IndexError example 2
mystring = "This is a short string."
print mystring[72]
IndexError                                Traceback (most recent call last)
<ipython-input-13-a36f79c41a37> in <module>()
      1 # IndexError example 2
      2 mystring = "This is a short string."
----> 3 print mystring[72]

IndexError: string index out of range

Using print statements to check code

Printing your code output as you write it is the only way to make sure that your code is doing what you think it is doing. By making sure, at each step, that your code produces the expected output, you can avoid introducing bugs and detect errors much more easily.

As a general rule-of-thumb, you should not write more then 2-5 lines of code without checking that it works before proceeding!!