(Python) inconsistent use of tabs and spaces in indentation

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Check out my new book

(Python) inconsistent use of tabs and spaces in indentation #

The Python "TabError: inconsistent use of tabs and spaces in indentation" occurs when we mix tabs and spaces in the same code block. To solve the error, remove the spacing and only use tabs or spaces, but don't mix the two in the same code block.

taberror inconsistent use of tabs and spaces in indentation

Here is an example of how the error occurs.

main.py
# ⛔️ TabError: inconsistent use of tabs and spaces in indentation if len('hi') == 2: print('a') print('b')

The first line in the code block was indented using tabs, and the second - using spaces and tabs.

mixing tabs and spaces

The screenshot shows that the print('a') line was indented using tabs (arrows), and the print('b') line was indented using spaces and tabs (dots and arrows).

To solve the error, remove the whitespace and only indent the lines in the code block using tabs or using spaces.

Make sure the lines of code in the code block at indented to the same level.

Your error message should show the exact location where the error is raised, so you can remove the whitespace and consistently indent the lines in the code block using tabs or spaces.

taberror inconsistent use of tabs and spaces in indentation

If you use VSCode, you can solve the error by using the "Convert indentation to spaces" or "Convert indentation to tabs" commands:

  1. press CTRL + Shift + P or ( + Shift + P on Mac) to open the command palette.
  2. type: "convert indentation to"
  3. Select your preferred option
  4. Save the file

vscode convert indentation to

If you use VSCode, you can show whitespace characters by:

  1. pressing CTRL + Shift + P or ( + Shift + P on Mac) to open the command palette.
  2. typing "open workspace settings"
  3. typing renderwhitespace
  4. setting it to all

vscode render whitespace

If you render whitespace characters in your IDE, tabs should show as arrows and spaces should show as dots.

mixing tabs and spaces

It is a matter of personal preference if you use only tabs or only spaces, but make sure not to mix the two.

Note that if you use tabs in one code block and spaces in the other, you won't get an error.

The error is only raised if you mix tabs and spaces in the same code block.

only using tabs or spaces

The upper if statement uses tabs for indentation, and the lower uses spaces.

The example doesn't cause an error because we didn't mix tabs and spaces in the same code block.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.