Common errors

What NameError, IndentationError, TypeError, IndexError, KeyError and EOFError mean and how to fix them.

Runs in Zerethon IDE · Python 3.12 Official Python documentation ↗

Read a traceback from the bottom: the last line names the error, the lines above show the file and line where it happened.

  • NameError: name 'x' is not defined — a typo, or the variable is used before it is assigned.
  • IndentationError / TabError — the lines of one block are not indented the same; use 4 spaces everywhere.
  • TypeError: can only concatenate str (not "int") to str — convert first: "Age: " + str(age), or use an f-string.
  • IndexError: list index out of range — the index is ≥ len(list); remember indexes start at 0.
  • KeyError: 'name' — the dict has no such key; use d.get("name") or check "name" in d.
  • ValueError: invalid literal for int() — the text is not a whole number (int("3.5"), int("")).
  • EOFError: EOF when reading a line — input() found no more input; fill in the Input tab.
  • ModuleNotFoundError — a third-party package, or a file name that does not match the import.
main.py
values = ["10", "x", "7"]
total = 0
for v in values:
    try:
        total += int(v)
    except ValueError:
        print(f"skipped {v!r}")
print("total:", total)

Output

skipped 'x'
total: 17
Handle an error you expect with try / except, naming the exception.