When i run my python script code, i meet error like this IndentationError: unindent does not match any outer indentation level. This error is so strange, and hard to find the reason. After some investigate, i finally find the solution.
1. Why Indentationerror.
Indentationerror error is always because of tab and white space mixed in your python code. We all know tab is used to present indentation in python. But as a coder, we may some times use white space to present the indentation. So if you mix used tab and white space for indentation, this error may occurred.
2. How To Locate Indentation Eerror.
When you run your python code, if the code has indentation error, it will throw the error message out to you which will make you struggled. The error message will tell you which line of code has indentation error.
C:\WorkSpace>test_sys_arg.py File "C:\WorkSpace\test_sys_arg.py", line 11 print('argv ' + str(i) + ' = ' + tmp_argv) ^ IndentationError: unindent does not match any outer indentation level
But you can also run python command
python -m tabnanny test_sys_arg.py to know which line of code has indentation error.
C:\WorkSpace>python -m tabnanny test_sys_arg.py 'test_sys_arg.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 11)
3. How To Fix Python Indentationerror.
We all know one tab contains four white space, so we need to know where we use four white space to replace one tab in python source code. Please follow below steps.
- Open your python souce file use one text editor like Sublime Text.
- Then press
Ctrl + Ato select all python souce code in the editor, then you can see at the beginning of line 11, there are four white space ( four dot ) that should be replaced with one tab.
- Replace the four white space with one tab at the beginning of line 11, save the file and run it again, you will find the error has been fixed.