IndentationErrors or indentation SyntaxErrors
suggest changeIn most other languages indentation is not compulsory, but in Python (and other languages: early versions of FORTRAN, Makefiles, Whitespace (esoteric language), etc.) that is not the case, which can be confusing if you come from another language, if you were copying code from an example to your own, or simply if you are new.
IndentationError/SyntaxError: unexpected indent
This exception is raised when the indentation level increases with no reason.
Example
There is no reason to increase the level here:
print("This line is ok")
print("This line isn't ok")
Here there are two errors: the last one and that the indentation does not match any indentation level. However just one is shown:
print("This line is ok")
print("This line isn't ok")
IndentationError/SyntaxError: unindent does not match any outer indentation level
This appears when you didn’t unindent completely.
Example
print("This line is ok")
print("This line isn't ok")
On Python 3.14 this one-space line raises unexpected indent. unindent does not match any outer indentation level is what you get when a later line returns to a column that is not an open indent level, such as 4 spaces followed later by 2.
IndentationError: expected an indented block
After a colon (and then a new line) the indentation level has to increase. This error is raised when that didn’t happen.
Example
if ok:
doStuff()
Note: Use the keyword pass (that does absolutely nothing) to just put an if, else, except, class, method or definition but not say what will happen if called/condition is true (but do it later, or in the case of except: just do nothing):
def foo():
pass
IndentationError: inconsistent use of tabs and spaces in indentation
Example
def foo():
if ok:
return "Two != Four != Tab"
return "i dont care i do whatever i want"
This sample uses only spaces. On Python 3.14 it raises unexpected indent, not inconsistent use of tabs and spaces. That message appears when one block mixes tab and space indents.
How to avoid this error
Don’t use tabs. It is discouraged by PEP8, the style guide for Python.
- Set your editor to use 4 spaces for indentation.
- Make a search and replace to replace all tabs with 4 spaces.
- Make sure your editor is set to display tabs as 8 spaces, so that you can realize easily that error and fix it.
See this question if you want to learn more.