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, what 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"
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"
print("This line is ok")
print("This line isn't ok")
IndentationError/SyntaxError: unindent does not match any outer indentation level
Appears you didn’t unindent completely.
Example
def foo():
print "This should be part of foo()"
print "ERROR!"
print "This is not a part of foo()"
print("This line is ok")
print("This line isn't ok")
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 makes 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"
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.