Python Error

Fix: IndentationError: unexpected indent

Exact message

IndentationError: unexpected indent

Quick answer

IndentationError: unexpected indent means a line has more leading whitespace than Python expects at that point. This almost always happens when you mix tabs and spaces, or when you accidentally indent a line that should be at the top level.

Why this error happens

Python uses indentation to delimit code blocks — no curly braces. If a line is indented without being inside a block (after if:, def:, for:, etc.), Python raises IndentationError. Mixing tabs (\t) and spaces is the most common trigger because the two look identical but count differently.

Example: Wrong vs Right

Wrong

def greet():
    print("hello")
        print("extra indent")
# IndentationError: unexpected indent

Right

def greet():
    print("hello")
    print("still inside function")

How to fix it (step by step)

  1. Open the file in an editor that shows whitespace characters (VS Code: View → Render Whitespace)
  2. Convert all tabs to 4 spaces (or all spaces to tabs — but be consistent)
  3. Ensure the failing line is at the same indent level as its siblings
  4. In VS Code, use 'Convert Indentation to Spaces' from the command palette

Frequently asked questions

Why does Python not allow mixed tabs and spaces?

In Python 3 (since 3.0), mixing tabs and spaces raises TabError, a subclass of IndentationError. Python 2 was lenient but inconsistent across editors — Python 3 forbids it.

What is the standard indent size?

PEP 8 recommends 4 spaces per indent level. Never use tabs in Python 3.

My code looks fine — how do I find the bad indent?

Use cat -A file.py or a whitespace-visible editor. The bad line will show ^I (tab) or an extra 4-space block.

Related Python errors

Need a fix for a different error?

Use the free to paste any traceback and get an AI-suggested fix in seconds.

Want an AI with memory for your project?

MonsterX AI remembers your codebase across chats.