Common Errors

When a program runs into a problem, it stops executing code and prints an error message. It is important to learn to read and interpret error messages in order to locate, troubleshoot, and fix problems (computer scientists call this process debugging). This page lists some of the more common Python errors related to the material in this course.

AI and Debugging

Generative AI models such as ChatGPT are very good at explaining error messages. However, if you are not careful, they will often also try fix your code for you. This violates the AI policy for this class.

Resist the temptation to immediately feed an error message to Google or an AI model. Instead, take the time to read and interpret the message. Doing so will help you understand the problem, internalize what went wrong, and avoid making the same mistake in the future. Debug in a way that leads to learning, not just assignment completion.

Error Messages

There are several types of errors, each indicating a different type of problem. This is the first clue in an error message as to what the issue is.

Name

Description

ImportError

The import statement has troubles trying to load a module.

IndexError

A sequence subscript is out of range.

NameError

A local or global name is not found.

SyntaxError

The parser encounters a syntax error.

TabError

Indentation contains an inconsistent use of tabs and spaces.

TypeError

An operation or function is applied to an object of inappropriate type.

ValueError

An operation or function receives an argument that has the right type but an inappropriate value.

ZeroDivisionError

The second argument of a division or modulo operation is zero.

Error messages point to the line of code where the problem occurred and conclude with a small description of what Python thinks the issue is. The following block of code starts to execute and produce outputs before resulting in an error.

x = 1
y = 2
z = 3

print(x)
print(why)
print(z)
1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 6
      2 y = 2
      3 z = 3
      4 
      5 print(x)
----> 6 print(why)
      7 print(z)

NameError: name 'why' is not defined

In this example, the error comes from the line print(why) and is due to the name why not existing.

Syntax Errors

Code that does not follow Python’s grammatical rules result in a SyntaxError. For example, a def statement to define a function must always end in :.

def f(x)
    return x**2
  Cell In[2], line 1
    def f(x)
            ^
SyntaxError: expected ':'

The ^ in the message attempts to point to the exact location of the problem.

Indentation

Clauses starting with :, such as function definitions or if clauses, must be indented consistently. Standard practice is to use four spaces for each indentation. Using the same indentation everywhere will make your code more readable and avoid errors that are visually difficult to detect.

def f(x):
return x**2
  Cell In[3], line 2
    return x**2
    ^
IndentationError: expected an indented block after function definition on line 1
if 1 < 2:
    print("indented with four spaces")
   print("indented with only three spaces")
  File <string>:3
    print("indented with only three spaces")
                                            ^
IndentationError: unindent does not match any outer indentation level
if 2 < 3:
  print("indented with two spaces")
    print("indented with four spaces")
  Cell In[5], line 3
    print("indented with four spaces")
    ^
IndentationError: unexpected indent

Mixing tabs characters and spaces is also not permitted. Most editors can be configured so that the tab key inserts four spaces instead of the literal \t tab character.

Has No Attribute: Misspelling

Some lab assignments ask you to store results as certain variables or to define certain functions. If the variables or functions are not spelled exactly correctly, you will likely see an error on Gradescope like the following.

Test Failed: module 'student_submission' has no attribute 'problem1_total'

This means that a variable problem1_total was expected, but no such variable actually exists, even if something close like problem1_totals does exist.

Single vs Double Equal Signs

One of the most common mistakes in Python is using = instead of == or vice versa.

  • == is a comparison operator that asks if two values are equal.

  • = assigns variables; it is not a comparison operator.

# Use == when attempting to assign a variable.
my_new_variable == 10
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 2
      1 # Use == when attempting to assign a variable.
----> 2 my_new_variable == 10

NameError: name 'my_new_variable' is not defined
my_new_variable = 10

# Use = when attempting to do a == comparison.
if my_new_variable = 10:
    print("It's ten!")
  Cell In[7], line 4
    if my_new_variable = 10:
       ^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Here is the correct usage.

my_new_variable = 10

if my_new_variable == 10:
    print("It's ten!")
It's ten!

Indexing

Entries of lists and NumPy arrays are accessed with square brackets, for example, x[i].

Calling vs Indexing

Parentheses () call a function, while square brackets [] index into a list or vector. Mixing these up results in a TypeError with a message about an object not being “subscriptable” or “callable.”

def my_function(x):
    return x + 1


# Index a function instead of calling it.
my_function[4]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 6
      2     return x + 1
      3 
      4 
      5 # Index a function instead of calling it.
----> 6 my_function[4]

TypeError: 'function' object is not subscriptable
x = [3, 1, 4, 1, 5, 2, 6, 5, 3, 5]

# Call a list instead of indexing it.
x(5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 4
      1 x = [3, 1, 4, 1, 5, 2, 6, 5, 3, 5]
      2 
      3 # Call a list instead of indexing it.
----> 4 x(5)

TypeError: 'list' object is not callable

Decimal Indices

An index for a list or NumPy array must be an int, not a float.

x = [3, 1, 4, 1, 5, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3]
print(x[6])     # Yes
print(x[7.0])   # No!
6
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 3
      1 x = [3, 1, 4, 1, 5, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3]
      2 print(x[6])     # Yes
----> 3 print(x[7.0])   # No!

TypeError: list indices must be integers or slices, not float

The place this becomes a problem is when using division to calculate an index, for example determining the index of the item in the middle of a list. The / operator always returns a float. Instead, use // to do integer division, which is regular division rounded down to an integer.

print(x[len(x) / 2])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 print(x[len(x) / 2])

TypeError: list indices must be integers or slices, not float
print(x[len(x) // 2])
3

Entry Zero

Indices start with zero, not one. A subtle error can be using the second item in a list or vector with x[1] when the first entry was meant to be used with x[0].

x = [2, 7, 8, 4, 6, 5, 1]
print(x[0])
print(x[1])
2
7

List Index Out of Range

If the value of an index is invalid, this can cause a IndexError. The most common way that this goes wrong is an off-by-one error, for instance using x[5] for a list or array with only 5 elements. Since indices start at 0, the largest possible index is 4.

x = [0, 5, 2, 6]

print(x[3])
print(x[4])
6
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[15], line 4
      1 x = [0, 5, 2, 6]
      2 
      3 print(x[3])
----> 4 print(x[4])

IndexError: list index out of range

These errors are especially common when using for loops. Consider the problem of finding the differences between each value in x and the value that comes before it: \(5 - 0 = 5\), \(2 - 5 = -3\), and \(6 - 2 = 4\). Here is a first attempt at this.

x = [0, 5, 2, 6]

for j in range(len(x)):
    print(x[j + 1] - x[j])
5
-3
4
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[16], line 4
      1 x = [0, 5, 2, 6]
      2 
      3 for j in range(len(x)):
----> 4     print(x[j + 1] - x[j])

IndexError: list index out of range

Here, len(x) equals 4, so in the for loop the variable j runs over the values 0, 1, 2, and 3. When j equals 3, the code in the loop tries to evaluate x[4] - x[3], which causes the problem. To fix this, recognize that there are only 3 differences to calculate.

x = [0, 5, 2, 6]

for j in range(len(x) - 1):
    print(x[j + 1] - x[j])
5
-3
4

Other Errors

When you encounter a new or unfamiliar error message, don’t panic! Read the error message carefully, find the problem, and try a few fixes yourself before turning to outside resources.