Inconsistent use of tabs and spaces in indentation ошибка

(Я совсем новичок)
Пишу в 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

Бронеслав's user avatar

БронеславБронеслав

1992 золотых знака6 серебряных знаков13 бронзовых знаков

5

В программировании на Питоне, отступы критичны!
Они используются языком для создания структуры программы (исходного кода).

Не стоит смешивать пробелы и табы.
А также надо следить за тем, чтобы отступы были все одинаковые и желательно кратные (например, по 4 пробела).

ответ дан 11 июл 2018 в 14:53

Kromster's user avatar

KromsterKromster

13.5k12 золотых знаков43 серебряных знака72 бронзовых знака

1

На взгляд обе эти коды одинаковыми, но во вашем коде вы в команде

            if i == 'o':

использовали 1 Tab и 8 пробелов, пока в команде

            print(i * 2, end='')

вы использовали 12 пробелов.

Дла человека в том нет разницы (т.к. Tab видит как 4 пробели), но Питону это не нравится.

ответ дан 11 июл 2018 в 15:11

MarianD's user avatar

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

longclaps

Что тут не понимать — скопипастил откуда-то кусок, а в нём табы. 3й питон считает ошибкой использование в одном файла одновременно как табов, так и пробелов.


Комментировать

Пригласить эксперта


Ответы на вопрос 1

sim3x

Косяк в том месте куда указал ^


Похожие вопросы


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

Table of Contents
Hide
  1. What is inconsistent use of tabs and spaces in indentation error?
  2. How to fix inconsistent use of tabs and spaces in indentation error?
    1. Python and PEP 8 Guidelines 
  3. 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.

  1. Press CTRL + Shift + P or (⌘ + Shift + P on Mac) to open the command palette.
  2. type “convert indentation to” in the search command palette
  3. select your preferred options, either tab or space

Vs Code Convert Indentation To Spaces Or Tabs

TabError: inconsistent use of tabs and spaces in indentation 2

Python and PEP 8 Guidelines 

  1. Generally, in Python, you follow the four-spaces rule according to PEP 8 standards
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. 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.

Avatar Of Srinivas Ramakrishna

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

TabError: inconsistent use of tabs and spaces in indentation-1

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

TabError: inconsistent use of tabs and spaces in indentation-1

So, always check the placing of tabs and spaces in your code properly. If you are using a text editor such as Sublime Text, use the option Convert indentation to spaces to make your code free from the “TabError: inconsistent use of tabs and spaces in indentation” error.

Are you getting the “TabError: inconsistent use of tabs and spaces in indentation” error while programming in Python?

In Python, you can use tabs and spaces to indent code. When you code, these are both seen as whitespaces. Therefore, the whitespace or indentation from the program’s first line must be preserved throughout the code. This can be four spaces, one tab, or a space. However, you must use a tab or a space to indent your code.

In this article, we’ll discuss the TabError: the inconsistent use of tabs and spaces in an indentation in Python, why it occurs, and how to fix ⚒️it. So without further ado, let’s dive deep into the topic.

Table of Contents
  1. Why Does The TabError: Inconsistent Use of Tabs And Spaces in Indentation Error Occurs?
  2. How to fix IndentationError: Unindent Does Not Match Any Outer Indentation Level in Python?

Why Does The TabError: Inconsistent Use of Tabs And Spaces in Indentation Error Occurs?

Python becomes confused if spaces and tabs are used interchangeably in a program. A “TabError: inconsistent use of tabs and spaces in indentation” error is then displayed. It is only possible to determine which lines of code belong in the if-else statement with the use of indentation.

Code

a = int(input("Enter a Number: "))


if a%2 == 0:

            print("Number is even ")

elif a%2 != 0:

         print("Number is odd")

   else:

       print("invalid")

Output

TabError inconsistent use of tabs and spaces in indentation

See the above example; extra tabs and spaces are used, which is why it gave an error: “IndentationError: unindent does not match any outer indentation level”.

How to fix IndentationError: Unindent Does Not Match Any Outer Indentation Level in Python?

To fix the error “IndentationError: unindent does not match any outer indentation level,” have two different alternate solutions.

  1. Eliminate extra spaces
  2. Select Untabify Region

Ensure that the code blocks’ lines of code are all indented to the same level. Make sure that if a new block is added in the middle of an existing one, the indentation for that block stays the same across the whole code. Verify that the indentation is consistent. Your error message should clearly identify the issue’s exact location so that you can eliminate any blank lines and regularly use tabs or spaces to indent the lines in the code block.

Code

a = int(input("Enter a number: "))

if a%2 == 0:

    print("Number is even")

elif a%2 != 0:

    print(" Number is odd")

else:

     print("invalid")

Output

Enter a number: 9

Number is odd

Verify for incorrect white spaces and tabs. An indentation mistake can’t be quickly fixed, unfortunately. Since the code is your own, you will still need to evaluate each line individually to spot any instances of errors.

 However, the procedure is rather straightforward because blocks of code are organized. If you have used the “if” statement, for instance, in a certain order, you can double-check to see if you have remembered to indent the line after it.

Method 2: Select Untabify Area

You may remove the indentation for a section of code in the IDLE editor by doing the following:

Choose the line of code whose indentation you wish to eliminate.

Select Menu -> Format -> Untabify area. Enter the indentation style you want to use.

If you’re using the IDLE editor, this is an easy method to fix the formatting of a document. The indentation of a file may be changed in many different editors, including Sublime Text, using their own procedures.

Conclusion

When we combine tabs and spaces in the same code block, Python throws the “TabError: inconsistent usage of tabs and spaces in indentation” error. Remove all spacing and only use tabs or spaces to fix the problem; never use both in the same code block.

You can resolve this error by removing white spaces. When you run the code, check where the interpreter has given the error and check for a specific line. 

If you are using IDLE Editor, so you can also select the complete code, and from the menu, you can select the format “Untabify Area”. After selecting the Format to “Untabify Area,” all the extra tabs and spaces will be removed from your code.

If you’ve found this article helpful, don’t forget to share and comment below 👇 which solutions have helped you solve the problem.

Zeeshan is a detail-oriented software engineer and technical content writer with a Bachelor’s in Computer Software Engineering and certifications in SEO and content writing. Thus, he has a passion for creating high-quality, SEO-optimized technical content to help companies and individuals document ideas to make their lives easier with software solutions. With over 150 published articles in various niches, including computer sciences and programming languages such as C++, Java, Python, HTML, CSS, and Ruby, he has a proven track record of delivering well-researched and engaging technical content.

Cover image for On "TabError: inconsistent use of tabs and spaces in indentation" in Python

Zeeshan is a detail-oriented software engineer and technical content writer with a Bachelor’s in Computer Software Engineering and certifications in SEO and content writing. Thus, he has a passion for creating high-quality, SEO-optimized technical content to help companies and individuals document ideas to make their lives easier with software solutions. With over 150 published articles in various niches, including computer sciences and programming languages such as C++, Java, Python, HTML, CSS, and Ruby, he has a proven track record of delivering well-researched and engaging technical content.

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The error “inconsistent use of tabs and spaces in indentation” occurs when you mix tabs and spaces to indent lines in a code block.

Here’s what it looks like:

File test.py, line 4
  print('tab')
        ^
TabError: inconsistent use of tabs and spaces in indentation

Enter fullscreen mode

Exit fullscreen mode

Sometimes the lines look perfectly aligned, but you still get the error. If that happens, chances are there’s a whitespace inconsistency in the respective indentation level.

You usually won’t have to worry about mixing spaces and tabs because most modern editors automatically convert tabs to spaces as your write code. However, if you copy a piece of code from the Internet (or another editor), you might have to check the indentation.

⚠️ Python disallows mixing spaces and tabs in the same indentation level — for instance, to indent the lines inside a for loop.

Although tabs and spaces are interchangeable, the Python style guide (PEP 8) recommends using spaces over tabs — four space characters per indentation level.

According to PEP 8, if you’re working with a code that’s already using tabs, you can continue using them to keep the indentation consistent.

To detect ambiguous indentation errors, you can use the tabnanny module:

dwd@dwd-sandbox:~$ python -m tabnanny test.py
test.py 4 "tprint('tab')"
In the above tabnanny output, line 4 is indented by a tab (t)

Enter fullscreen mode

Exit fullscreen mode

How to fix the «unindent does not match any outer indentation level» error

To avoid this situation, you can make all whitespaces visible in your code editor. These indicators give you quick feedback as you write code.

Additionally, you can automatically turn all unwanted tabs into spaces without re-indenting each line manually.

Here’s how to do it with three popular code editors:

  • Visual Studio Code
  • Sublime Text
  • Vim

Visual Studio Code: To make whitespace characters (space or tab) visible in VS code, press ⌘+Shift+P (on Mac) or Ctrl+Shift+P (on Windows) to open up the command palette. Then, type Toggle Render Whitespaces and hit enter (↵)

As a result, VS Code will display space characters as gray dots and tabs as tiny arrows.

And to make whitespaces consistent, in the command palette, run Convert Indentation to Spaces or Convert Indentation to Tabs accordingly.

Sublime Text: If you have a space/tab indentation issue on Sublime Text, go to View ➝ Indentation and select Indent Using Spaces.

You can also highlight your code (Ctrl + A) to see the whitespaces in your code.

Vim: In Vim, you can use the :retab command to convert tabs into spaces automatically.

And to make whitespace characters visible in Vim:

First, run the following Vim command:

:set list

Enter fullscreen mode

Exit fullscreen mode

And then run:

:set listchars=space:␣,tab:-> 

Enter fullscreen mode

Exit fullscreen mode

You can replace and with the characters of your choice.

Alright, I think that does it! I hope you found this quick guide helpful.

Thanks for reading.


❤️ You might like:

  • TypeError: missing 1 required positional argument: ‘self’ (Fixed)
  • Unindent does not match any outer indentation level error in Python (Fixed)
  • AttributeError module ‘DateTime’ has no attribute ‘strptime’ (Fixed)
  • AttributeError: ‘str’ object has no attribute ‘decode’ (Fixed)
  • How back-end web frameworks work?

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.

Get offers and scholarships from top coding schools illustration

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

Email

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!

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! 👍

Понравилась статья? Поделить с друзьями:
  • Incomplete session by time out ошибка принтера samsung
  • Incoming packet was garbled on decryption ошибка
  • Incoming client packet has caused exception starbound ошибка
  • Including corrupted data ошибка принтера xerox phaser
  • Include stdafx h ошибка как исправить