Dealing with errors

Objectives

  • Be able to interpret Python error messages.
  • Know the common error types and how they arise.

During the course of your programming, it is inevitable that you will make errors. Programming languages are generally very unforgiving of even seemingly minor departures from what they expect, and Python is no exception. When encountering such a situation, the program will tend to raise an error by displaying a message to the screen and ceasing any further processing.

Hence, an important part of programming is knowing how to interpret error messages and to fix their underlying causes. Here, we will go through some of the common errors in Python programming.

Tip

Here, we will be dealing with a class of errors that cause Python to cease functioning. There is a more insidious form of error called a logic error, in which the program executes without any apparent problems but the way the program is written does not implement the desired outcome correctly.

Consequences of errors

What happens when your Python code contains an error? Here, we will have a look at what happens when we try and print the contents of a variable that we haven’t defined.

print apples
Traceback (most recent call last):
  File "", line 1, in <module>
    print apples
NameError: name 'apples' is not defined

As you can see, Python prints out an error message. There are three main useful components of such messages:

  1. The line number where the error occurred.
    This is not always completely accurate, but it gives you an idea of the location in your code that is causing the error.
  2. The type of error.
    Python has several different classes of error; here, we have committed what is referred to as a NameError.
  3. The additional information.
    After the type of error, the message often prints out a more detailed explanation of what went wrong. Here, it tells us that the variable name apples has not been defined.

Types of error—NameError

This class of error is encountered when Python does not recognise the name of something in a statement. As we saw above, this can happen when we try and refer to a variable that has not been defined. It was quite obvious in that example, but it can also happen because of typos:

apples = 2

print appples
Traceback (most recent call last):
  File "", line 3, in <module>
    print appples
NameError: name 'appples' is not defined

You might also encounter a NameError if you are trying to create a string but forget to include the quotation marks (this might also give you another form of error, depending on what characters were in the string that you are trying to make):

hello_str = Hello
Traceback (most recent call last):
  File "", line 1, in <module>
    hello_str = Hello
NameError: name 'Hello' is not defined

Another reason that you may encounter a NameError is forgetting to use an appropriate import statement before using additional functionality. For example:

print random.random()
Traceback (most recent call last):
  File "", line 1, in <module>
    print random.random()
NameError: name 'random' is not defined

Why do we get a name error here? Because we had not yet imported the random package:

import random

print random.random()
0.775627301052

Note that these statements are executed sequentially, so the import statement needs to come before you try and use it:

print random.random()

import random
Traceback (most recent call last):
  File "", line 1, in <module>
    print random.random()
NameError: name 'random' is not defined

Types of error—SyntaxError

This class of error is encountered with Python is unable to parse a section of the code—that is, if its construction does not conform to a format that Python can interpret.

For example, Python does not know what you mean if you try and name a variable starting with a number. The way it communicates this is via a SyntaxError:

4apples = 4
  File "", line 1
    4apples = 4
          ^
SyntaxError: invalid syntax

A SyntaxError can also be raised if you try and use an operator that Python doesn’t know about in a particular context. For example:

print 2 $ 3
  File "", line 1
    print 2 $ 3
            ^
SyntaxError: invalid syntax

Finally, you may also run across a SyntaxError if you forget the colon in a loop or conditional:

if 2 > 1
    print "A"
  File "", line 1
    if 2 > 1
           ^
SyntaxError: invalid syntax

Note that you will can also encounter a SyntaxError if using code written for Python version 2 (as on this site) but executing it with Python version 3. For example, Python 3 changed the way the print operator works. If you run the code print "Hello, world!" in Python 3, you would get an error like:

File "", line 1
  print "Hello, world!"
                  ^
SyntaxError: Missing parentheses in call to 'print'

Types of error—IndentationError

Python is very picky about indentation, as it needs to be—as we have seen, indentation is used to indicate program structure. As such, it needs to be used consistently throughout your code.

Our convention is to use four space characters (inserted using the TAB key) to indicate an indented block. You will find that if this is not used correctly, an IndentationError will be raised:

for i in range(2):
print i
  File "", line 2
    print i
        ^
IndentationError: expected an indented block

Python here is quite useful in telling you what went wrong—it expected an indented block after a for statement but didn’t find one. Here is a slightly different example, where Python is unable to unambiguously determine which level of indentation a statement belongs to:

for i in range(2):
    for j in range(2):
        print i
      print j
  File "", line 4
    print j
          ^
IndentationError: unindent does not match any outer indentation level

Types of error—TypeError

This form of error is encountered when there is something wrong with the data type that is used for a particular operation or function. We have seen this error before when we try to combine data types using an operator that it doesn’t know what to do with. For example, dividing a string by a number doesn’t make much sense:

print "Hello" / 3
Traceback (most recent call last):
  File "", line 1, in <module>
    print "Hello" / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'

We can also encounter a TypeError when we give a function more arguments than it is expecting. For example, the abs function returns the absolute value of a numerical argument. If we give it more than one, it raises a TypeError:

print abs(-3)
print abs(-3, 5)
3
Traceback (most recent call last):
  File "", line 2, in <module>
    print abs(-3, 5)
TypeError: abs() takes exactly one argument (2 given)

We also get an error if we don’t give a function enough arguments:

print abs()
Traceback (most recent call last):
  File "", line 1, in <module>
    print abs()
TypeError: abs() takes exactly one argument (0 given)

Types of error—IndexError

We encounter an IndexError when we try and access an element of a collection beyond the number of elements that the collection contains. For example, with a list:

apples = range(5)
print apples[10]
Traceback (most recent call last):
  File "", line 2, in <module>
    print apples[10]
IndexError: list index out of range

We can also get a similar error from a string:

hello_str = "Hello, World!"
print hello_str[20]
Traceback (most recent call last):
  File "", line 2, in <module>
    print hello_str[20]
IndexError: string index out of range

Types of error—AttributeError

This class of error is encountered when trying to use a function or variable attached a data (which as known as an attribute) that is not present. For example, we have seen that strings have a set of attached functions. We may have thought that there was such a function named sum—however, if we tried to use it we would encounter an AttributeError:

hello_str = "Hello, World!"
print hello_str.sum()
Traceback (most recent call last):
  File "", line 2, in <module>
    print hello_str.sum()
AttributeError: 'str' object has no attribute 'sum'