/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
printf 'print("a")\n print("b")\n' > bad.py
python bad.pyOutput · exit 1
File "/tmp/work/bad.py", line 2
print("b")
IndentationError: unexpected indentThe file is never executed: the error is raised while compiling, so print("a") does not run either.
Related indentation errors
The same family has three other messages, each with a different cause:
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
doneOutput
== 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
| Message | Meaning |
|---|---|
| IndentationError: unexpected indent | A line is indented although no block was opened |
| IndentationError: expected an indented block | A line ending in : is not followed by an indented body |
| IndentationError: unindent does not match any outer indentation level | A dedent goes back to a column that no outer block uses |
| TabError: inconsistent use of tabs and spaces in indentation | Tabs and spaces are mixed in a way whose meaning depends on the tab width |
Find the problem lines
printf 'if True:\n\ta = 1\n b = 2\n' > mixed.py
python -m tabnanny -v mixed.pyOutput
'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
Related pages
errors · pythonModuleNotFoundError: No module named '…'Python raises ModuleNotFoundError when the package is not installed for the interpreter that runs your code. Check sys.executable, then install with -m pip.errors · pythonTypeError: 'NoneType' object is not subscriptablePython raises this TypeError when you index a value that is None, often the result of list.sort(), dict.get() or re.match(). Find where None comes from.commands · pythonpython -m json.tool: pretty-print and validate JSONPretty-print or validate JSON from the shell with python -m json.tool (or python -m json on 3.14+). Sort keys, set indent, compact output and read JSON Lines.