(Я совсем новичок)
Пишу в IDLE (Python 3.4.1 shell) Когда копирую код из интернета, он ошибки не выдаёт, а когда я его переписываю буква в букву, он выдаёт ошибку.
вот код из интернета:
>>>for i in 'hello world':
if i == 'o':
continue
print(i * 2, end='')
Вот мой:
>>> for i in 'hello world':
if i == 'o':
continue
print(i * 2, end='')
SyntaxError: inconsistent use of tabs and spaces in indentation
В чём ошибка?
Оказывается ошибка была не только в отступах.
Если в питоне вы не правильно написали какую то строчку и после неё нажали Enter, то после этого программа может вместо переноса на новую строчку прогнать программу. Когда у меня такое было, я что бы избежать прогона вместо исправления ошибки переходил на новую строчку долгим нажатием на пробел, а уже потом исправлял ошибку. В результате программа видела не отступ, а длинную строчку. И выдавала ошибку! Спасибо всем большое. Ошибка устранена.
НА вопрос в коментарии: Я учусь по смоучителю в интернете https://pythonworld.ru/samouchitel-python
задан 11 июл 2018 в 14:28
БронеславБронеслав
1992 золотых знака6 серебряных знаков13 бронзовых знаков
5
В программировании на Питоне, отступы критичны!
Они используются языком для создания структуры программы (исходного кода).
Не стоит смешивать пробелы и табы.
А также надо следить за тем, чтобы отступы были все одинаковые и желательно кратные (например, по 4 пробела).
ответ дан 11 июл 2018 в 14:53
KromsterKromster
13.5k12 золотых знаков43 серебряных знака72 бронзовых знака
1
На взгляд обе эти коды одинаковыми, но во вашем коде вы в команде
if i == 'o':
использовали 1 Tab и 8 пробелов, пока в команде
print(i * 2, end='')
вы использовали 12 пробелов.
Дла человека в том нет разницы (т.к. Tab видит как 4 пробели), но Питону это не нравится.
ответ дан 11 июл 2018 в 15:11
MarianDMarianD
14.1k3 золотых знака18 серебряных знаков29 бронзовых знаков
@hardtime88
IT любитель и начинающий специалист
При написании парсера столкнулся с ошибкой
course = {'titel': titel, 'descript': descript, 'url': url}
^
TabError: inconsistent use of tabs and spaces in indentation
не понимаю где косяк с табуляцией
-
Вопрос заданболее трёх лет назад
-
21768 просмотров
2
комментария
Решения вопроса 1
Что тут не понимать — скопипастил откуда-то кусок, а в нём табы. 3й питон считает ошибкой использование в одном файла одновременно как табов, так и пробелов.
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Косяк в том месте куда указал ^
Похожие вопросы
-
Показать ещё
Загружается…
09 июн. 2023, в 01:21
10000 руб./за проект
09 июн. 2023, в 01:06
50000 руб./за проект
09 июн. 2023, в 00:36
1000 руб./за проект
Минуточку внимания
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.
TabError inconsistent use of tabs and spaces in indentation
In Python, You can indent using tabs and spaces in Python. Both of these are considered to be whitespaces when you code. So, the whitespace or the indentation of the very first line of the program must be maintained all throughout the code. This can be 4 spaces, 1 tab or space. But you must use either a tab or a space to indent your code.
But if you mix the spaces and tabs in a program, Python gets confused. It then throws an error called “TabError inconsistent use of tabs and spaces in indentation”.
In this article, we delve into the details of this error and also look at its solution.
How to fix ‘TabError: inconsistent use of tabs and spaces in indentation’?
Example:
a = int(input("Please enter an integer A: "))
b = int(input("Please enter an integer B: "))
if b > a:
print("B is greater than A")
elif a == b:
print("A and B are equal")
else:
print("A is greater than B")
Output:
TabError: inconsistent use of tabs and spaces in indentation
When the code is executed, the “TabError inconsistent use of tabs and spaces in indentation”. This occurs when the code has all the tabs and spaces mixed up.
To fix this, you have to ensure that the code has even indentation. Another way to fix this error is by selecting the entire code by pressing Ctrl + A. Then in the IDLE, go to the Format settings. Click on Untabify region.
Solution:
1. Add given below line at the beginning of code
#!/usr/bin/python -tt
2. Python IDLE
In case if you are using python IDLE, select all the code by pressing (Ctrl + A) and then go to Format >> Untabify Region
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.