Skip to content

/errors/python/indentationerror-unexpected-indent

Python: IndentationError: unexpected indent

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated
tool
Python
exit code
1
versions
Python 3.x
os
any

IndentationError: unexpected indent means a line starts with more indentation than Python expects at that point. Indentation is part of Python's syntax: a deeper indent is only allowed right after a line that opens a block (if, for, def, class, with, try, all ending in :). The traceback points at the offending line; align it with its neighbours.

Reproduce it

bash
printf 'print("a")\n    print("b")\n' > bad.py
python bad.py

Output · exit 1

  File "/tmp/work/bad.py", line 2
    print("b")
IndentationError: unexpected indent

The file is never executed: the error is raised while compiling, so print("a") does not run either.

The same family has three other messages, each with a different cause:

bash
printf 'if True:\nprint("x")\n' > no_block.py
printf 'if True:\n        a = 1\n    b = 2\n' > dedent.py
printf 'if True:\n\ta = 1\n        b = 2\n' > mixed.py
for f in no_block.py dedent.py mixed.py; do
  echo "== $f"; python "$f" 2>&1 | tail -n 1
done

Output

== no_block.py
IndentationError: expected an indented block after 'if' statement on line 1
== dedent.py
IndentationError: unindent does not match any outer indentation level
== mixed.py
TabError: inconsistent use of tabs and spaces in indentation
MessageMeaning
IndentationError: unexpected indentA line is indented although no block was opened
IndentationError: expected an indented blockA line ending in : is not followed by an indented body
IndentationError: unindent does not match any outer indentation levelA dedent goes back to a column that no outer block uses
TabError: inconsistent use of tabs and spaces in indentationTabs and spaces are mixed in a way whose meaning depends on the tab width

Find the problem lines

bash
printf 'if True:\n\ta = 1\n        b = 2\n' > mixed.py
python -m tabnanny -v mixed.py

Output

'mixed.py': *** Line 3: trouble in tab city! ***
offending line: '        b = 2'
inconsistent use of tabs and spaces in indentation

cat -A file.py (GNU coreutils) also shows tabs as ^I, which makes mixed indentation visible.

Sources