ErrorPython

IndentationError: unexpected indent

Why Python raises IndentationError: unexpected indent, how mixed tabs and spaces cause it invisibly, and how to fix the offending line for good.

Last updated

ErrorPython
  File "script.py", line 4
    print("hello")
IndentationError: unexpected indent

What it means: Python found a line indented further than the surrounding code expects, with nothing before it — like a `:` that opens a new block — that would justify starting an indented block there.

Likely causes

Most probable first — with how to confirm.

  • 1.Mixed tabs and spaces within the same file — they can look identical in some editors, but Python 3 treats inconsistent tab/space mixing within a block as an error; check your editor's 'show whitespace' setting.
  • 2.A stray extra space or two at the start of a line, often from pasting code copied out of a webpage, PDF, or a source with a different indent width — check the exact column of the flagged line against the lines around it.
  • 3.The line is indented under a statement that doesn't actually open a block — a missing `:` on the preceding `if`, `for`, or `def` line — or the line simply doesn't belong indented at all.

Fixes

Safest first; destructive ones are called out.

  • Turn on 'render whitespace' in your editor and fix the offending line to match the indentation of the block it belongs to — the fastest fix once tabs and spaces are visible.
  • Standardize on spaces (PEP 8 recommends 4, no tabs) and set your editor to insert spaces on Tab; most editors can also auto-convert an existing file's tabs to spaces.
  • Run `python -tt script.py` to have Python itself flag inconsistent tab/space use specifically, which pinpoints the exact mixed line rather than just the symptom.
  • If the code was pasted from an external source, re-indent that block by hand rather than trusting whatever whitespace came along with the paste.

Related in Errors