Dealing with errors#

Attention

Finnish university students are encouraged to use the CSC Notebooks platform.
CSC badge

Others can follow the lesson and fill in their student notebooks using Binder.
Binder badge

Interpreting error messages#

So far in the course we have encountered a number of different types of error messages in Python, but have not really discussed how to understand what the computer is trying to tell you when you get an error message. We’ll do that below. For most Python errors you will see and exception raised when the error is encountered, providing some insight into what went wrong and where to look to fix it.

Reading error messages#

Let’s imagine you’ve written the code below called to convert wind speeds from km/hr to m/s and you’re dying to figure out how windy it is in Halifax, Nova Scotia, Canada where they report wind speeds in km/hr.

Unfortunately, when you run your script you observe the following:

wind_speed_km = 50
wind_speed_ms = wind_speed_km * 1000 / 3600

print(f"A wind speed of {wind_speed_km} km/hr is {wind_speed_ms} m/s.)
  Cell In[1], line 4
    print(f"A wind speed of {wind_speed_km} km/hr is {wind_speed_ms} m/s.)
          ^
SyntaxError: unterminated string literal (detected at line 4)

Let’s break this example down and see what the error message says.

Syntax error A SyntaxError, annotated

As you can see, there is quite a bit of useful information here. We have some information about the code cell that was run, as well as which line of the cell was a problem. We also have the type of error, a SyntaxError in this case, where it occurred on the line, and a bit more information about its meaning. The location on the line won’t always be correct, but Python makes its best guess for where you should look to solve the problem. In this case, we can see that our f-string is missing the second set of quotation marks.

Let’s consider another example, where you have fixed the SyntaxError above and now have made a function for calculating a wind speeds in m/s.

When you run this script you encounter a new and bigger error message:

def convert_wind_speed(speed):
    return speed * 1000 / 3600

wind_speed_km = '30'
wind_speed_ms = convert_wind_speed(wind_speed_km)

print(f"A wind speed of {wind_speed_km} km/hr is {wind_speed_ms} m/s.")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 5
      2     return speed * 1000 / 3600
      4 wind_speed_km = '30'
----> 5 wind_speed_ms = convert_wind_speed(wind_speed_km)
      7 print(f"A wind speed of {wind_speed_km} km/hr is {wind_speed_ms} m/s.")

Cell In[2], line 2, in convert_wind_speed(speed)
      1 def convert_wind_speed(speed):
----> 2     return speed * 1000 / 3600

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

In this case we see a TypeError that is part of a traceback, where the problem in the code arises from something other than on the line where the code was run. In this case, we have a TypeError where we try to divide a character string by a number, something Python cannot do. Hence, the TypeError indicating the data types are not compatible. That error, however, does not occur when the code is run until the point where the function is used. Thus, we see the traceback showing that not only does the error occur when the function is called, but also that the problem is in the function definition (note the two arrows indicating the problem lines).

The traceback above may look a bit scarier, but if you take your time and read through what is output, you will again find that the information is helpful in finding the problem in your code. After all, the purpose of the error message is to help the user find a problem :).

Error messages in Python 3.10 and newer

Our course environment is using Python 3.10 which was released in October 2021. Among the changes in this release are improvements in the error messages that are generated for many of the cases below. Nice!

Common errors and exceptions#

Now that we have some idea of how to read an error message, let’s have a look at a few different types of common Python exceptions that are displayed for different program errors.

IndexErrors#

An IndexError occurs when you attempt to reference a value with an index outside the range of values. We can easily produce an IndexError by trying to access the value at index 5 in the following list of cities: cities = ['Paris', 'Berlin', 'London'].

cities = ["Paris", "Berlin", "London"]
cities[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[4], line 1
----> 1 cities[5]

IndexError: list index out of range

Here we get the rather clear error message that the index used for the list cities is outside of the range of index values for that list.

NameErrors#

A NameError typically occurs when you reference a variable that has not been defined. We can produce a NameError by trying station_id = stations[1].

station_id = stations[1]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 1
----> 1 station_id = stations[1]

NameError: name 'stations' is not defined

In this instance we receive a NameError because the list stations has not been defined, and we’re thus not able to access a value in that list.

IndentationErrors#

An IndentationError is raised whenever a code block is expected to be indented and is either (1) not indented, or (2) is indented inconsistently. Let’s see this in two examples below.

for city in cities:
    city = city + " is a city in Europe"
  print(city)
  File <tokenize>:3
    print(city)
    ^
IndentationError: unindent does not match any outer indentation level
for city in cities:
city = city + " is a city in Europe"
print(city)
  Cell In[8], line 2
    city = city + " is a city in Europe"
    ^
IndentationError: expected an indented block after 'for' statement on line 1

In both of the examples above, an IndentationError is raised. In the first case, the indentation level is inconsistent. In case two, indentation is expected for the code below a for statement.

TypeErrors#

A TypeError is raised whenever two incompatible data types are used together. For example, if we try to divide a character string by a number or add a number to a boolean variable, a TypeError will be raised.

cities[0] / 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 1
----> 1 cities[0] / 5

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

In this case, the TypeError is because it is not possible to divide a character string by a number.

Other kinds of errors#

There are certainly other kinds of errors and exceptions in Python, but this list comprises those you’re most likely to encounter. As you can see, knowing the name of each error can be helpful in trying to figure out what has gone wrong, and knowing what these common error types mean will save you time trying to fix your programs.

More information on errors#

You can find a bit more information about reading error messages on the Software Carpentry and Python Software Foundation webpages.