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,whileortrythe 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 blockCorrect:
def greet(name):
print("Hello", name)Solutions
- Use four spaces per level and stay consistent everywhere.
- Make tabs visible in the editor and convert them to spaces (VS Code: “Convert Indentation to Spaces”).
- A line without content? Then write
pass. - Find mixed forms with
python -m tabnanny file.py. - Use a formatter such as Black or Ruff.
See also: ModuleNotFoundError