Dealing with errors¶
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:
[1]:
wind_speed_km = 50
wind_speed_ms = wind_speed_km * 1000 / 3600
print('A wind speed of', wind_speed_km, 'km/hr is', wind_speed_ms, 'm/s.)
File "<ipython-input-1-75d8ffbf5ea6>", line 4
print('A wind speed of', wind_speed_km, 'km/hr is', wind_speed_ms, 'm/s.)
^
SyntaxError: EOL while scanning string literal
Let’s break this example down and see what the error message says.
A SyntaxError, annotated
As you can see, there is quite a bit of useful information here. We have the name of the script, its location, and which line was a problem. It’s always good to double check that you actually are editing the correct script when looking for errors! We also have the type of error, a SyntaxError
in this case, as well as 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. Clearly, this is handy information.
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:
[2]:
def convert_wind_speed(speed):
return speed * 1000 / 3600
wind_speed_km = '30'
wind_speed_ms = convert_wind_speed(wind_speed_km)
print('A wind speed of', wind_speed_km, 'km/hr is', wind_speed_ms, 'm/s.')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/opt/python/3.8.0/lib/python3.8/codeop.py in __call__(self, source, filename, symbol)
131
132 def __call__(self, source, filename, symbol):
--> 133 codeob = compile(source, filename, symbol, self.flags, 1)
134 for feature in _features:
135 if codeob.co_flags & feature.compiler_flag:
TypeError: required field "type_ignores" missing from Module
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 used, but also that the problem is in the function definition.
The traceback above may look a bit scarier, but if you take your time and read through what is written there, 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 :).
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']
.
[3]:
cities = ['Paris', 'Berlin', 'London']
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/opt/python/3.8.0/lib/python3.8/codeop.py in __call__(self, source, filename, symbol)
131
132 def __call__(self, source, filename, symbol):
--> 133 codeob = compile(source, filename, symbol, self.flags, 1)
134 for feature in _features:
135 if codeob.co_flags & feature.compiler_flag:
TypeError: required field "type_ignores" missing from Module
[4]:
cities[5]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-34a99c8a1728> in <module>()
----> 1 cities[5]
NameError: name 'cities' is not defined
Here we get the rather clear error message that the index used for the list cities
is out of the range of index values for that list.
NameErrors¶
A NameError
occurs when you reference a variable that has not been defined. We can produce a NameError
by trying station_id = stations[1]
.
[5]:
station_id = stations[1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/opt/python/3.8.0/lib/python3.8/codeop.py in __call__(self, source, filename, symbol)
131
132 def __call__(self, source, filename, symbol):
--> 133 codeob = compile(source, filename, symbol, self.flags, 1)
134 for feature in _features:
135 if codeob.co_flags & feature.compiler_flag:
TypeError: required field "type_ignores" missing from Module
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 not, or is indented inconsistently. Let’s consider two examples below.
[6]:
for city in cities:
city = city + ' is a city in Europe'
print(city)
File "<ipython-input-6-d01719aec99a>", line 3
print(city)
^
IndentationError: unindent does not match any outer indentation level
[7]:
for city in cities:
city = city + ' is a city in Europe'
print(city)
File "<ipython-input-7-b86b26f34739>", line 2
city = city + ' is a city in Europe'
^
IndentationError: expected an indented block
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.
[8]:
cities[0] / 5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-9aba02c90a51> in <module>()
----> 1 cities[0] / 5
NameError: name 'cities' is not defined
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¶
You can find a bit more information about reading error messages on the Software Carpentry and Python Software Foundation webpages.