@hardtime88
IT любитель и начинающий специалист
При написании парсера столкнулся с ошибкой
course = {'titel': titel, 'descript': descript, 'url': url}
^
TabError: inconsistent use of tabs and spaces in indentation
не понимаю где косяк с табуляцией
-
Вопрос заданболее трёх лет назад
-
18918 просмотров
2
комментария
Решения вопроса 1
Что тут не понимать — скопипастил откуда-то кусок, а в нём табы. 3й питон считает ошибкой использование в одном файла одновременно как табов, так и пробелов.
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Косяк в том месте куда указал ^
Похожие вопросы
-
Показать ещё
Загружается…
12 февр. 2023, в 22:43
5000 руб./за проект
09 февр. 2023, в 13:28
777 руб./за проект
12 февр. 2023, в 21:32
80000 руб./за проект
Минуточку внимания
Table of Contents
Hide
- What is inconsistent use of tabs and spaces in indentation error?
- How to fix inconsistent use of tabs and spaces in indentation error?
- Python and PEP 8 Guidelines
- Conclusion
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.
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)
Output
File "c:PersonalIJSCodeprgm.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))
Output
10000
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.
Conclusion
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.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
You can indent code using either spaces or tabs in a Python program. If you try to use a combination of both in the same block of code, you’ll encounter the “TabError: inconsistent use of tabs and spaces in indentation” error.
In this guide, we discuss what this error means and why it is raised. We’ll walk through an example of this error so you can figure out how to solve it in your code.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
TabError: inconsistent use of tabs and spaces in indentation
While the Python style guide does say spaces are the preferred method of indentation when coding in Python, you can use either spaces or tabs.
Indentation is important in Python 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.
Consider the following program:
numbers = [8, 7, 9, 8, 7] def calculate_average_age(): average = sum(numbers) / len(numbers) print(average)
Without indentation, it is impossible to know what lines of code should be part of the calculate_average_age function and what lines of code are part of the main program.
You must stick with using either spaces or tabs. Do not mix tabs and spaces. Doing so will confuse the Python interpreter and cause the “TabError: inconsistent use of tabs and spaces in indentation” error.
An Example Scenario
We want to build a program that calculates the total value of the purchases made at a donut store. To start, let’s define a list of purchases:
purchases = [2.50, 4.90, 5.60, 2.40]
Next, we’re going to define a function that calculates the total of the “purchases” list:
def calculate_total_purchases(purchases): total = sum(purchases) return total
Our function accepts one parameter: the list of purchases which total value we want to calculate. The function returns the total value of the list we specify as a parameter.
We use the sum() method to calculate the total of the numbers in the “purchases” list.
If you copy this code snippet into your text editor, you may notice the “return total” line of code is indented using spaces whereas the “total = sum(purchases)” line of code uses tabs for indentation. This is an important distinction.
Next, call our function and print the value it returns to the console:
total_purchases = calculate_total_purchases(purchases) print(total_purchases)
Our code calls the calculate_total_purchases()
function to calculate the total value of all the purchases made at the donut store. We then print that value to the console. Let’s run our code and see what happens:
File "test1.py", line 5 return total ^ TabError: inconsistent use of tabs and spaces in indentation
Our code returns an error.
The Solution
We’ve used spaces and tabs to indent our code. In a Python program, you should stick to using either one of these two methods of indentation.
To fix our code, we’re going to change our function so that we only use spaces:
def calculate_total_purchases(purchases): total = sum(purchases) return total
Our code uses 4 spaces for indentation. Let’s run our program with our new indentation:
Our program successfully calculates the total value of the donut purchases.
In the IDLE editor, you can remove the indentation for a block of code by following these instructions:
- Select the code whose indentation you want to remove
- Click “Menu” -> “Format” -> “Untabify region”
- Insert the type of indentation you want to use
This is a convenient way of fixing the formatting in a document, assuming you are using the IDLE editor. Many other editors, like Sublime Text, have their own methods of changing the indentation in a file.
Conclusion
The Python “TabError: inconsistent use of tabs and spaces in indentation” error is raised when you try to indent code using both spaces and tabs.
You fix this error by sticking to either spaces or tabs in a program and replacing any tabs or spaces that do not use your preferred method of indentation. Now you have the knowledge you need to fix this error like a professional programmer!