← Back to Blog
    TutorialOctober 14, 20266 min read

    Python Error Messages Explained (and How to Fix Them)

    Learn to read a Python traceback and fix the nine errors beginners meet most: SyntaxError, IndentationError, NameError, TypeError, ValueError and more.

    On this page

    Every programmer sees error messages every day. They are not a sign that you are bad at coding. They are Python telling you, as precisely as it can, what went wrong and where. Once you know how to read them, most errors take seconds to fix.

    This guide shows how to read a traceback, then walks through the nine errors beginners meet most often, each with a broken example and the fix.

    How to read a traceback

    When a program crashes, Python prints a traceback. Here is one from a small program that works out an average:

    def average(numbers):
        return sum(numbers) / len(numbers)
    
    print(average([]))
    Traceback (most recent call last):
      File "main.py", line 4, in <module>
        print(average([]))
              ^^^^^^^^^^^
      File "main.py", line 2, in average
        return sum(numbers) / len(numbers)
               ~~~~~~~~~~~~~^~~~~~~~~~~~~~
    ZeroDivisionError: division by zero

    Read it from the bottom up:

    1. The last line names the error and describes it: a ZeroDivisionError, because the list was empty, so its length was 0.
    2. The lines just above show exactly where it happened: line 2, inside the average function. The markers under the code point at the part that failed.
    3. The lines further up show how the program got there: line 4 called average.

    In the PythonExecutor terminal you get the short version, which is often all you need: Line 2: ZeroDivisionError: division by zero.

    SyntaxError

    A SyntaxError means Python cannot understand your code as written, so nothing runs at all. Missing quotes, brackets and colons are the usual causes.

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

    The closing quote is missing. Here is another common one:

    age = 15
    if age > 12
        print("Teenager")
    SyntaxError: expected ':'

    Lines that start a block, such as if, for, while and def, must end with a colon. If a SyntaxError points at a line that looks fine, check the line above it for an unclosed bracket or quote.

    IndentationError

    Python uses indentation, the spaces at the start of a line, to group code into blocks. An IndentationError means those spaces do not line up.

    def greet():
    print("Hi")
    IndentationError: expected an indented block after function definition on line 1

    The body of the function must be indented. Use four spaces:

    def greet():
        print("Hi")

    The opposite mistake, indenting a line that should not be, gives IndentationError: unexpected indent.

    NameError

    A NameError means you used a name that Python does not know. Usually it is a typo, or a variable used before it was created.

    message = "Hi"
    print(mesage)
    NameError: name 'mesage' is not defined. Did you mean: 'message'?

    Recent versions of Python even suggest the name you probably meant. Remember that names are case sensitive too: Print and print are different.

    TypeError

    A TypeError means you used a value in a way its type does not allow, most often mixing text and numbers:

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

    You cannot join a string and a number with +. Convert the number with str(age), or use an f-string, which does it for you:

    age = 12
    print(f"Age: {age}")

    The same error appears when you do maths on the result of input(), which is always text. Convert it with int() first.

    ValueError

    A ValueError means the type is right but the value is not usable:

    number = int("twelve")
    ValueError: invalid literal for int() with base 10: 'twelve'

    int() accepts text, but only text that looks like a whole number. When the text comes from a user, wrap the conversion in try and except ValueError and ask again.

    IndexError

    An IndexError means you asked for a position that does not exist in a list or string:

    colors = ["red", "green", "blue"]
    print(colors[3])
    IndexError: list index out of range

    Positions start at 0, so a list of three items has positions 0, 1 and 2. To get the last item without counting, use colors[-1].

    KeyError

    A KeyError is the dictionary version: you looked up a key that is not there.

    ages = {"Ana": 12, "Ben": 14}
    print(ages["Cara"])
    KeyError: 'Cara'

    Check first with if "Cara" in ages:, or use ages.get("Cara", 0), which gives you a default value instead of crashing.

    AttributeError

    An AttributeError means a value does not have the method or property you asked for. It often happens when you borrow a name from another language:

    numbers = [3, 1, 2]
    numbers.add(4)
    AttributeError: 'list' object has no attribute 'add'

    Lists use append, so the fix is numbers.append(4). The message tells you the type (list), which helps you look up the right method.

    ZeroDivisionError

    Dividing by zero is impossible, so Python refuses:

    scores = [8, 9, 10]
    count = 0
    print(sum(scores) / count)
    ZeroDivisionError: division by zero

    Before dividing by something that could be zero, check it: if count > 0:.

    A routine for any error

    When you meet an error you have not seen before, work through these steps:

    1. Read the last line of the message: the error type and what it says.
    2. Go to the line number it gives you.
    3. For a SyntaxError, also check the line above.
    4. Add print() calls to see what your variables hold just before the crash.
    5. Still stuck? Search for the error type and message exactly as written.

    Quick reference

    ErrorUsually meansCheck first
    SyntaxErrorPython cannot read the codeQuotes, brackets and colons
    IndentationErrorSpaces at the start of lines do not line upFour spaces per level
    NameErrorUnknown nameSpelling and capital letters
    TypeErrorWrong kind of valueMixing text and numbers
    ValueErrorRight kind, unusable valueConverting user input
    IndexErrorPosition past the endCounting starts at 0
    KeyErrorMissing dictionary keyUse .get() or in
    AttributeErrorMethod does not existThe type named in the message
    ZeroDivisionErrorDividing by zeroThe divisor before dividing

    The fastest way to get comfortable with errors is to cause them on purpose. Open the PythonExecutor playground, paste in any broken example from this guide, run it, and then fix it.

    By PythonExecutor Team

    Related Articles