Solving problem is about exposing yourself to as many situations as possible like IndentationError: unindent does not match any outer indentation level and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about IndentationError: unindent does not match any outer indentation level, which can be followed any time. Take easy to follow this discuss.
When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys def Factorial(n): # Return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",result return result
Other posters are probably correct…there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",result return result print Factorial(10)
Sublime Text users:
Sublime Text to use tabs for indentation:
Convert Indentation to Tabs
Indent Using Spaces option as well in the same sub-menu above.
This will immediately resolve this issue.
To easily check for problems with tabs/spaces you can actually do this:
python -m tabnanny yourfile.py
or you can just set up your editor correctly of course 🙂
Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)
Note, it is recommended that you don’t use tabs in Python code. See the style guide. You should configure Notepad++ to insert spaces for tabs.
Whenever I’ve encountered this error, it’s because I’ve somehow mixed up tabs and spaces in my editor.
If you use Python’s IDLE editor you can do as it suggests in one of similar error messages:
1) select all, e.g. Ctrl + A
2) Go to Format -> Untabify Region
3) Double check your indenting is still correct, save and rerun your program.
I’m using Python 2.5.4
If you are using Vim, hit escape and then type
This auto indents everything and will clear up any spaces you have thrown in.
result = result * i should be indented (it is the body of the for-loop).
Or – you have mixed space and tab characters