Python errors

Python Errors and How to Fix Them

When a program stops with an error, the last line of its message names the error. Find it here: what it means, what to check, and the usual causes, each shown broken and fixed.

  • AttributeError The value has no method or attribute by that name. The message names the value's type and what was asked for. AttributeError: 'list' object has no attribute 'split'
  • FileNotFoundError Python couldn't find the file to open. Its name is looked up next to your program, so the file has to be there with exactly that name. FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
  • IndentationError The spaces at the start of a line don't fit the block it belongs to. Python uses indentation to know which lines belong together. IndentationError: expected an indented block after 'if' statement on line 2
  • IndexError A position was asked for that the list or string doesn't have. IndexError: list index out of range
  • KeyError The dictionary has no such key. Python names the key it looked for after KeyError. KeyError: 'name'
  • ModuleNotFoundError Python couldn't find the module to import: its name is spelled differently, the file isn't in the project, or the package isn't installed here. ModuleNotFoundError: No module named 'maths'
  • NameError Python reached a name it has no value for: a variable, function or module it hasn't seen created yet. NameError: name 'total' is not defined
  • RecursionError A function kept calling itself and never stopped. Python stops it after about 1,000 calls. RecursionError: maximum recursion depth exceeded
  • SyntaxError Python couldn't read your code, so none of it ran. The mistake is on the line the message points to, or just above it. SyntaxError: invalid syntax
  • TypeError A value was used in a way its type doesn't allow, like adding text to a number or calling something that isn't a function. TypeError: can only concatenate str (not "int") to str
  • UnboundLocalError A function used a variable before giving it a value. Assigning to a name anywhere in a function makes it that function's own variable. UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
  • ValueError The value has the right type but one Python can't use, like the text "12.50" given to int(). ValueError: invalid literal for int() with base 10: 'abc'
  • ZeroDivisionError A number was divided by zero, which has no answer. The zero is usually a count or a length that came out empty. ZeroDivisionError: division by zero