EMZETT.
Login

IndentationError (Python)

In short: Python reports that the indentation of a line does not match the surrounding code.

In more detail: Python uses indentation instead of curly braces to form blocks. If the indentation is wrong, the interpreter aborts before running. Typical messages: IndentationError: unexpected indent, expected an indented block and unindent does not match any outer indentation level.

In Depth

Possible causes

  • After if, for, def, class, while or try the indented block is missing.
  • Tabs and spaces mixed (looks the same but is not).
  • A line is accidentally indented or not indented.
  • Code copied from the internet with wrong formatting.

Example

def greet(name):
print("Hello", name)   # IndentationError: expected an indented block

Correct:

def greet(name):
    print("Hello", name)

Solutions

  1. Use four spaces per level and stay consistent everywhere.
  2. Make tabs visible in the editor and convert them to spaces (VS Code: “Convert Indentation to Spaces”).
  3. A line without content? Then write pass.
  4. Find mixed forms with python -m tabnanny file.py.
  5. Use a formatter such as Black or Ruff.

See also: ModuleNotFoundError