How to fix TabError: inconsistent use of tabs and spaces in indentation

When running Python code, you might encounter the following error:

TabError: inconsistent use of tabs and spaces in indentation

This error occurs because your Python code uses a mix of tabs and spaces to indent your code blocks.

Python doesn’t use curly brackets to denote the beginning and the end of a code block. Instead, you need to use indentations.

How to reproduce this error

Let’s see an example that causes this error. Suppose you have a function named greet() that has two lines of code as follows:

def greet():
  name = "Nathan"
	print("Hello", name)

When you run this code, you’ll get an error saying:

  File "main.py", line 3
    print("Hello", name)
TabError: inconsistent use of tabs and spaces in indentation

This error occurs because the first line in the function use spaces, but the second line uses a tab.

While you can use both to indent your Python code, you need to use only one for the entire code in one file.

How to fix this error

To resolve this error, you need to change the indentation of your code to use one indentation notation.

Python coding style guide prefers spaces over tabs, so let’s follow it.

You need to change the code to use 4 spaces for each nested code:

def greet():
    name = "Nathan"
    print("Hello", name)

Now that the indentations are fixed, you should be able to run the code without receiving the error.

Conclusion

The TabError: inconsistent use of tabs and spaces in indentation occurs in Python when you use both spaces and tabs to indent your source code.

To fix this error, you need to use only one indent method for the entire source file. If you use spaces, then remove any tabs that appear in your code, and vice versa.

I hope this tutorial is helpful. See you in other articles! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.