IndentationError in Python — What It Means and How to Fix It

What Python's IndentationError exception means and how to resolve it.

Published October 27, 2026

IndentationError is raised when Python's required indentation is inconsistent: mixing tabs and spaces or wrong levels.

What it means and why it happens

Python uses indentation to define blocks, so each block must be consistently indented (4 spaces by convention).

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
IndentationError: unexpected indent

Practical examples

Code that triggers it

def f():
print('hi')

The fix

def f():
    print('hi')

Auto-format

python -m black file.py
python -tt file.py   # detect tab/space mix

Common mistakes

  • Mixing tabs and spaces.
  • Copy-pasting code with different indentation.
  • Forgetting to indent after a colon.

Key takeaways

  • IndentationError: IndentationError is raised when Python's required indentation is inconsistent: mixing tabs and spaces or wrong levels.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Tabs or spaces?

Use 4 spaces and configure your editor.

How do I find which line caused IndentationError?

The error message and stack trace show the file and line; start there and work backwards.

More Python articles