← All Articles

Python IndentationError: Unexpected Indent — Causes & Fixes

What Does This Error Mean?

Python uses indentation as part of its syntax — unlike C or Java where braces define blocks. An IndentationError means the whitespace structure of your code doesn't match what Python expects. There are three variants you'll actually see:

  • IndentationError: unexpected indent — a line is indented more than it should be
  • IndentationError: expected an indented block — a block starter (if/for/def) has no indented body
  • IndentationError: unindent does not match any outer indentation level — the dedent level doesn't line up with any previous level

Common Causes

  • Mixing spaces and tabs (the classic — invisible in most editors)
  • An empty if/for/def block with just a comment
  • Extra spaces before a line that shouldn't be indented
  • Copy-pasting code from the web/PDFs that preserves odd whitespace
  • An editor set to tab-width that differs from Python's expectations

How to Fix It

1. Standardize on 4 spaces (PEP 8)

# Bad — mixed indentation
if x > 0:
        print(x)
	print("done")  # tab here

# Good — consistent 4 spaces
if x > 0:
    print(x)
    print("done")

2. Make tabs visible in your editor — VS Code: Ctrl+Shift+P → Toggle Render Whitespace. PyCharm: Settings → Editor → General → Appearance → Show whitespace. Tabs render as arrows, spaces as dots — you'll see the mix instantly.

3. Fix empty blocks with pass

# Bad — empty block
if condition:

# Good
if condition:
    pass  # placeholder until you implement the logic

4. Let the formatter fix it — run black your_file.py or autopep8 --in-place your_file.py. Both normalize all indentation to 4 spaces and end the tabs-vs-spaces war permanently.

5. Find the exact line — the error message includes line numbers: File "app.py", line 12. The error line is where the mismatch is, but the root cause is often a few lines above (a block that wasn't closed properly).

Why It Happens to Everyone

If you're coming from JavaScript or C, your muscle memory presses tab to 'just indent it visually.' Python reads that whitespace as structure — an extra indent opens a new block that never closes, and everything after it breaks. The fix is a habit: indent once when you enter a block, dedent exactly once when you leave it, and never use the tab key at all if you can help it.