IndentationError: unindent does not match
1 · The lesson
readWhat this error means
Python's indentation is part of its grammar. Every nested block starts at one column, and every line in that block must start at exactly that column. When a line moves back to the left (unindents), it must line up with an outer block that started 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. One column off. You typed one space too few or too many when you re-indented code, so a line that should start at column 4 starts 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 consistent. If it prints something, it shows you the line with the problem.
2. Convert all tabs to spaces. Choose one style and use it everywhere. 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 you can see the wrong line immediately.
4. Re-indent the whole block if you are not sure. Select the function, delete the whitespace at the start of the lines and indent them again in the same way. This is faster than searching for the wrong 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 will see this error much less often.
When you'd see this in real code
- Editing a file that someone else wrote with tabs while your editor inserts spaces: every line you change becomes a mix of both.
- 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
Found this useful? Share it with a friend who’s learning Python.