Errors tell us when the program we've written isn't working properly, but they also tell us a lot about what is wrong with the program to help us fix it. Let's look at a simple example where we try to add a string and a number together. Python isn't sure what to do, so it tells us that we aren't allowed to do this by reporting an error.

In [1]:
print("The temperature today is: " + 75)
TypeError                                 Traceback (most recent call last)
<ipython-input-1-73b2a512c1d6> in <module>()
----> 1 print("The temperature today is: " + 75)

TypeError: cannot concatenate 'str' and 'int' objects

The first line of the error tells us what kind of error has occurred. It's a TypeError, which tells us that it has something to do with converting between types or combining different types.

The second two lines tell us where the error occurred. The in <module>() part tells us that the error is happening directly in the code that we are working on and ----> 1 print tells us that it's occuring on the first line. This isn't particularly useful in this simple case, because we only have one line of code that doesn't call any external modules, but knowing where the error occurred is very useful when writing larger programs.

Finally, the last line tells us exactly what went wrong. The error informs us that we cannot concatenate strings and integers, which is what we are trying to doing using the +.

Another common error occurs when you accidentally reference a variable that doesn't exist yet. For example,

In [2]:
body_mass_kg = 25
body_mass_g = bodymass_kg * 1000
NameError                                 Traceback (most recent call last)
<ipython-input-2-0d766c7eb65c> in <module>()
      1 body_mass_kg = 25
----> 2 body_mass_g = bodymass_kg * 1000

NameError: name 'bodymass_kg' is not defined

The error message tells us that:

  1. The error is a NameError so it has something to do with a variable name
  2. It occurs in line 2 of the code we are writing
  3. That we asked for a variable named bodymass_kg that doesn't exist yet

The reason that bodymass_kg doesn't exist is because there is a typo in the name, it should be body_mass_kg. This is a very common type of error.

Read Error Messages Carefully

One of the most common mistakes that new programmers make is to see an error try to figure out what is wrong with their code without actually carefully reading the error message. Always taking a few seconds to read the error message will help you find the location of the error and understand how you should fix it much more quickly.