[Solved] : Python TabError: inconsistent use of tabs and spaces in indentation


In Python, TabError is sub class of IndentationError. Python allows code style by using indentation by space or tabs. If you are using both while writing code for indentation then Python encounter “TabError : inconsistent use of tabs and spaces in indentation”.

In Python, Indentation is important because the language doesn’t depend on syntax like curly brackets to denote where a block of code starts and finishes . Indents tell Python what lines of code are part of what code blocks.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can see complete Python exception hierarchy through this link : Python: Built-in Exceptions Hierarchy.

Example

Consider a below scenario where indentation is use by implementing space and tab both on line 3 (used space for indentation) while in line 4 (used tabs for indentation). When you will run the below program it will throw exception as mentioned in output.

numbers = [3.50, 4.90, 6.60, 3.40]
def calculate_total(purchases):
	total = sum(numbers)
        return total
total_numbers = calculate_total(numbers)
print(total_numbers)

Output

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 10
return total
^
TabError: inconsistent use of tabs and spaces in indentation

Solution

To resolve this issue, you have done some minor change in your code for indentation by either space or tabs and run the program will work fine.

numbers = [3.50, 4.90, 6.60, 3.40]
def calculate_total(purchases):
    total = sum(numbers)
    return total
total_numbers = calculate_total(numbers)
print(total_numbers)

Output

18.4

Learn Python exception handling in more detain in topic Python: Exception Handling

Let me know your thought on it.

Happy Learning !!!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s