Table of Contents Hide
The TabError: inconsistent use of tabs and spaces in indentation occurs if you indent the code using a combination of whitespaces and tabs in the same code block.
What is inconsistent use of tabs and spaces in indentation error?
In Python, indentation is most important as it does not use curly braces syntax like other languages to denote where the code block starts and ends.
Without indentation Python will not know which code to execute next or which statement belongs to which block and this will lead to IndentationError.
We can indent the Python code either using spaces or tabs. The Python style guide recommends using spaces for indentation. Further, it states Python disallows mixing tabs and spaces for indentation and doing so will raise Indentation Error.
Let us look at an example to demonstrate the issue.
In the above example, we have a method
convert_meter_to_cm(), and the first line of code is indented with a tab, and the second line is indented with four white spaces.
def convert_meter_to_cm(num): output = num * 1000 return output convert_meter_to_cm(10)
File "c:\Personal\IJS\Code\prgm.py", line 3 return output ^ TabError: inconsistent use of tabs and spaces in indentation
When we execute the program, it clearly shows what the error is and where it occurred with a line number.
How to fix inconsistent use of tabs and spaces in indentation error?
We have used both spaces and tabs in the same code block, and hence we got the error in the first place. We can resolve the error by using either space or a tab in the code block.
Let us indent the code according to the PEP-8 recommendation in our example, i.e., using four white spaces everywhere.
def convert_meter_to_cm(num): output = num * 1000 return output print(convert_meter_to_cm(10))
If you are using the VS Code, the easy way to solve this error is by using the settings “Convert indentation to spaces” or “Convert indentation to tabs” commands.
- Press CTRL + Shift + P or (⌘ + Shift + P on Mac) to open the command palette.
- type “convert indentation to” in the search command palette
- select your preferred options, either tab or space
Python and PEP 8 Guidelines
- Generally, in Python, you follow the four-spaces rule according to PEP 8 standards.
- Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
- Do not mix tabs and spaces. Python disallows the mixing of indentation.
- Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.
If you mix both tabs and spaces for indentation in the same code block Python will throw inconsistent use of tabs and spaces in indentation. Python is very strict on indentation and we can use either white spaces or tabs in the same code block to resolve the issue.