Module 1 · Beginner · Getting started

Python error messages and tracebacks explained

How to read Python error messages and tracebacks, with the 10 most common errors beginners see (SyntaxError, NameError, TypeError and more) and how to fix them.

By theprogrammers team · · 7 min read

Every programmer sees errors every day, from beginners to people with twenty years of experience. The difference is that experienced programmers read the error message instead of panicking. A Python error message tells you what went wrong, on which line, and often how to fix it.

This guide shows how to read a traceback, then walks through the ten errors you'll see most often as a beginner, with the exact message Python prints and the fix for each.

Reading a traceback

Here's a small program with a bug. Save it as shop.py:

def average(marks):
    return sum(marks) / len(marks)


scores = []
print("Calculating...")
print(average(scores))

Running it prints:

Calculating...
Traceback (most recent call last):
  File "shop.py", line 7, in <module>
    print(average(scores))
          ~~~~~~~^^^^^^^^
  File "shop.py", line 2, in average
    return sum(marks) / len(marks)
           ~~~~~~~~~~~^~~~~~~~~~~~
ZeroDivisionError: division by zero

A traceback is the trail of function calls that led to the error. Read it from the bottom up:

  1. The last line is the most important. It names the error type, ZeroDivisionError, and describes it: "division by zero".
  2. Just above it is where it happened: line 2 of shop.py, inside the function average. The ^ marks point at the exact operation, the /.
  3. Further up is how the program got there: line 7 called average(scores). <module> means the main part of the file, outside any function.

So the story is: line 7 called average with an empty list, and line 2 divided by len([]), which is 0. The fix is to handle the empty case:

def average(marks):
    if not marks:
        return 0
    return sum(marks) / len(marks)

Copy the last line of a traceback into a search engine and you'll usually find the fix. Leave out your own file names and variable names.

Two kinds of errors

  • Syntax errors happen before the program runs. Python reads the whole file first, and if it isn't valid Python, nothing runs at all.
  • Runtime errors (also called exceptions) happen while the program runs, when a line can't do what it asks. Everything before that line has already run, which is why "Calculating..." was printed above.

The 10 errors you'll meet most

1. SyntaxError: the code isn't valid Python

if 5 > 3
    print("yes")
    if 5 > 3
            ^
SyntaxError: expected ':'

Fix: add the missing colon. Other common causes are missing brackets and quotes:

    print("hello)
          ^
SyntaxError: unterminated string literal (detected at line 1)

When the error points at a line that looks correct, check the line above it for an unclosed bracket.

2. IndentationError: wrong spaces at the start of a line

if True:
print("x")
IndentationError: expected an indented block after 'if' statement on line 1

Fix: indent the lines that belong to the if by four spaces. Don't mix tabs and spaces; VS Code turns the Tab key into four spaces for .py files.

3. NameError: Python doesn't know this name

pritn("hi")
NameError: name 'pritn' is not defined. Did you mean: 'print'?

Causes: a typo, using a variable before creating it, a wrong capital letter (Name vs name), or forgetting the quotes around text. Python even suggests the fix here.

4. TypeError: the wrong type for this operation

age = 20
print("Age: " + age)
TypeError: can only concatenate str (not "int") to str

Fix: you can't add text and a number. Use an f-string, print(f"Age: {age}"), or convert with str(age).

5. ValueError: the right type, but a bad value

int("abc")
ValueError: invalid literal for int() with base 10: 'abc'

Fix: int() needs text that looks like a whole number. This often comes from input(). Python input and type conversion shows how to keep asking until the user types a valid number.

6. ZeroDivisionError: dividing by zero

As in the traceback above. Fix: check that the number you divide by isn't zero first.

7. IndexError: a position that doesn't exist

n = [1, 2]
n[5]
IndexError: list index out of range

Fix: a list with 2 items has positions 0 and 1 only. Check len(), and remember counting starts at 0. See Python lists.

8. KeyError: a dictionary key that doesn't exist

d = {"a": 1}
d["b"]
KeyError: 'b'

Fix: check the spelling, use "b" in d to test first, or use d.get("b"), which returns None instead of crashing. See Python dictionaries.

9. AttributeError: this type doesn't have that method

"hi".push("x")
AttributeError: 'str' object has no attribute 'push'

Fix: the value isn't the type you think, or the method has a different name. Here, strings have no push, and lists use append, not push. If the message says 'NoneType' object has no attribute, a variable you expected to hold something is None, often because a function didn't return a value.

10. ModuleNotFoundError: Python can't find a module

import requestz
ModuleNotFoundError: No module named 'requestz'

Fix: check the spelling. If it's a third-party package, install it with python -m pip install requests, using the same Python that runs your code. In VS Code, check the interpreter shown in the bottom bar.

Quick reference

ErrorUsually means
SyntaxErrorMissing colon, bracket or quote
IndentationErrorMissing or inconsistent indentation
NameErrorTypo, or the variable doesn't exist yet
TypeErrorMixing types, such as text + number
ValueErrorConverting text that isn't a number
ZeroDivisionErrorDividing by zero
IndexErrorPosition past the end of a list or string
KeyErrorMissing dictionary key
AttributeErrorWrong method name, or the value is None
ModuleNotFoundErrorTypo in an import, or the package isn't installed

A debugging routine that works

  1. Read the last line of the traceback: the error type and message.
  2. Go to the line it points to, and look at the ^ marks.
  3. Print the values just before that line: print(marks, type(marks)). Most bugs are a variable holding something you didn't expect.
  4. Change one thing and run again.
  5. Still stuck? Search for the last line of the error, or explain the problem out loud to someone, or to a rubber duck. Explaining it often reveals the answer.

Key takeaways

  • Read a traceback from the bottom: error type and message, then the line, then how the code got there.
  • Syntax errors stop the program before it starts; runtime errors stop it at the failing line.
  • Most beginner errors are typos, missing colons, wrong indentation, or mixing text and numbers.
  • print() the values before the failing line to see what's really there.

Practice

Find and fix the bug in each program.

  1. This should print "Hello, Ahana".
name = "Ahana"
print("Hello, " + Name)
Show the answer

NameError: name 'Name' is not defined. Python is case-sensitive: use name, as in print("Hello, " + name).

  1. This should print the total price.
price = 50
quantity = input("Quantity: ")
print(price * quantity)
Show the answer

input() returns a string, so 50 * "3" gives "333..." (the text repeated 50 times), not 150. Convert it: quantity = int(input("Quantity: ")).

  1. This should print the last fruit.
fruits = ["apple", "mango", "banana"]
print(fruits[3])
Show the answer

IndexError: list index out of range. Three items have positions 0, 1 and 2. Use fruits[2], or better, fruits[-1], which always gives the last item.

  1. This should print "Adult".
age = 20
if age >= 18
    print("Adult")
Show the answer

SyntaxError: expected ':'. Add the colon: if age >= 18:.

Interview questions

What is the difference between a syntax error and an exception?

A syntax error means the code isn't valid Python, so it's caught when the file is parsed and nothing runs. An exception happens while the program runs, when an operation fails, and it can be caught and handled with try and except.

How do you read a Python traceback?

From the bottom up. The last line gives the exception type and message. The lines above show the call stack: each file, line number and function, from the outermost call at the top to the line that raised the error at the bottom.

What is the difference between TypeError and ValueError?

A TypeError means an operation got a value of the wrong type, such as "5" + 5. A ValueError means the type is right but the value isn't acceptable, such as int("abc"): int() accepts strings, but not that one.

What to learn next

  1. Start the basics module with Python variables and data types.
  2. Learn to catch errors with try and except in Python file handling.