# 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 [3]:
for i in range(5):
print(w)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-bf59bc2e88a1> 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. 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, or alternatively to print an actual variable that exists.

In [4]:
for i in range(5):
print(i)

0
1
2
3
4


And now, the code works properly with no errors. There are many other types of "standard errors" like NameError (see here: https://docs.python.org/3/library/exceptions.html), 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 [5]:
# SyntaxError example 1
# Missing a closing bracket at the end of list definition

mylist = [1,2,3,4

  File "<ipython-input-5-ff4a1be089c5>", line 4
mylist = [1,2,3,4
^
SyntaxError: unexpected EOF while parsing

In [6]:
# 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-6-ff67bfdf796f>", line 6
print(a b)
^
SyntaxError: invalid syntax

In [7]:
# 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-7-269618f8c53b>", line 5
for f in fruit
^
SyntaxError: invalid syntax


## IndentationError¶

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 [8]:
# IndentationError example
if 7 > 9:
print("7 is greater than 9")

  File "<ipython-input-8-f4371a687dea>", line 3
print("7 is greater than 9")
^
IndentationError: expected an indented block

In [9]:
# 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-9-6fb062e572cb>", line 4
print(i)
^
IndentationError: unexpected indent


## ValueError¶

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

In [10]:
# ValueError example
number = "mystring!"
x = int(number)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-23fc41a4fe9e> in <module>()
1 # ValueError example
2 number = "mystring!"
----> 3 x = int(number)

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

## TypeError¶

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 [11]:
# TypeError example 1
a = 7
lengtha = len(a)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-5f7dc742a60b> in <module>()
1 # TypeError example 1
2 a = 7
----> 3 lengtha = len(a)

TypeError: object of type 'int' has no len()
In [12]:
# TypeError example 2 - you can't subtract from strings!
a = "this is a string"
b = a - 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-b2b8dc1f3b54> in <module>()
1 # TypeError example 2 - you can't subtract from strings!
2 a = "this is a string"
----> 3 b = a - 1

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

## KeyError¶

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

In [13]:
# KeyError example
d = {"seven": 7, "nine": 9, "eleven": 11}
print(d["five"])

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

KeyError: 'five'

## IndexError¶

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

In [14]:
# IndexError example 1
mylist = [11, 22, 33, 44, 55, 66]
print(mylist[9])

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-14-328e34f02d47> 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 [15]:
# IndexError example 2
mystring = "This is a short string."
print(mystring[72])

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
IndexError: string index out of range