When I run my python script code, I meet an 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 investigation, I finally find the solution.
1. Why IndentationError.
Indentationerror error is always because of tab and white space mixed in your python code. We generally use 4 white spaces to present indentation in python. But as a coder, we may sometimes use the tab key to present the indentation. So if you mix used white space and tab for indentation, this error may occur.
2. How To Locate Indentation Error.
When you run your python code, if the code has an 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 an 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 the python command
python -m tabnanny test_sys_arg.py to know which line of code has an 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 spaces, so we need to know where we use four white spaces to replace one tab in python source code. Please follow the below steps.
- Open your python source file use one text editor like Sublime Text.
- Then press
Ctrl + Ato select all python source code in the editor, then you can see at the beginning of line 11, there are four white spaces ( four dots) 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.
- There is also a shortcut in Sublime text which can help you to make conversion between tab to spaces.
- Click the View —> Indentation menu item in Sublime text, then it will list some sub-menu items.
- Click the Convert Indentation to Spaces or Convert Indentation to Tabs menu item can do the tab and spaces conversion.
- You can also specify to use white spaces for indentation by checking the Indent Using Spaces submenu item.
- Or you can select how many spaces that one tab will contain by choosing different Tab Width values.