IndentationError: unindent does not match
1 · The lesson
readWhat this error means
Python's indentation is part of its grammar. Every nested block must start at one consistent column and every line in that block must sit at exactly that column. When a line "comes back out" (unindents), it must line up with an outer block that was opened at the same column. This error means it doesn't.
When you see it
>>> def greet(name): ... if name: ... print("hi") ... print("done") File "<stdin>", line 4 print("done") ^ IndentationError: unindent does not match any outer indentation level
Why it happens
Two main causes:
1. Mixed tabs and spaces. A tab and four spaces look identical in many editors, but Python treats them as different characters. A block opened with spaces cannot be continued with tabs (and vice versa).
2. Off-by-one column. You hit space once too few or too many when re-indenting after a refactor, so a line that should sit at column 4 actually sits at column 3 or 5.
How to fix it
1. Run tabnanny — it reports any ambiguous indentation:
python -m tabnanny script.py
If it prints nothing, your indentation is internally consistent. If not, it points at the offending line.
2. Convert all tabs to spaces. Pick one and stick with it; PEP 8 recommends four spaces. Most editors have a "convert indentation to spaces" command:
- VS Code: command palette -
Convert Indentation to Spaces. - PyCharm:
Code - Reformat Code. - Vim:
:retab. - From the shell:
expand -t 4 script.py > fixed.py.
3. Show whitespace in your editor. Turning on "render whitespace" makes tabs (often shown as >) and spaces (.) visible, so the offending line stands out immediately.
4. Re-indent the whole block if in doubt. Select the function, delete the leading whitespace, and re-add it consistently. This is faster than hunting for the bad character.
5. Configure your editor to insert spaces on Tab. In VS Code, set "editor.insertSpaces": true and "editor.tabSize": 4. Once your editor is set up correctly, you'll never see this error again.
When you'd actually see this in real code
- Editing a file that someone else wrote with tabs while your editor inserts spaces — every line you touch becomes a mix.
- Pasting indented code from a web page into a terminal-based editor that doesn't translate tabs.
- Working across editors and operating systems where default indent settings differ.
Related errors
See Also
- All Python errors — the full index, by type and by when it happens.
- Python syntax cheat sheet
- PEP 8 style tutorial