392

I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.

How can I change the spaces into tabs? It's driving me crazy.

import random

attraktioner = ["frittfall","bergodalbana","spökhuset"]


class Nojesfalt:
    def __init__(self, attraktion):
        self.val = attraktion
        self.langd = 0
        self.alder = 0


#längdgräns för fritt fall
    def langdgrans(self):
        print("")
        self.langd = int(input("Hur lång är du i cm? "))
        if self.langd < 140:
            print("tyvärr, du är för kort, prova något annat")
            return 0
        elif self.langd >= 140:
            print("håll dig hatten, nu åker vi!")
            print(" ")
            return 1

#åldersgräns för spökhuset
    def aldersgrans(self):
        print("")
        self.alder = int(input("Hur gammal är du? "))
        if self.alder < 10:
            print("tyvärr, du är för ung, prova något annat")
            return 0
        elif self.alder >= 10:
            print("Gå in om du törs!")
            print(" ")
            return 1


#åker attraktion frittfall lr bergodalbana
        def aka(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("åkturen gick åt skogen, bättre lycka nästa gång")
        elif tal >= 20:
            print("jabbadabbbadoooooooo")
            return 1

#går i spökhuset
        def aka1(self):
                print("")
        print(self.val)
        tal = random.randint(0,100)
        if tal < 20:
            print("du är omringad av spöken och kan inte fortsätta")            return 0
        elif tal >= 20:
            print("Buhuuuuuu, buuuhuuuu")
            return 1

#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")

while 1:
    vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
    if vald_attr == "1":
        val = Nojesfalt(attraktioner[0])
        if val.langdgrans() == 1:
            val.aka()
    elif vald_attr == "2":
        val = Nojesfalt(attraktioner[1])
        val.aka()
    elif vald_attr == "3":
        val = Nojesfalt(attraktioner[2])
        if val.aldersgrans() == 1:
            val.aka1()
    elif vald_attr == "4":
        break
wovano
  • 4,543
  • 5
  • 22
  • 49
Julia Lärkert
  • 3,961
  • 3
  • 15
  • 3
  • 45
    That's an issue with your code editor, not really with python. You should change your question to reflect that and mention what editor you are using. – Jeff Mercado Apr 16 '11 at 08:49
  • 4
    How you change this depends on your editor. I'm not sure this is even on-topic here, it might be a question for superuser. – Lennart Regebro Apr 16 '11 at 10:10
  • 1
    Change your editor to show visible whitespace at the start of the line. For example, I have configured my editor to show transparent tabs and visible spaces because I use tabs to indent code. If I see any noise at the start of the line, I know that there're one or more extra spaces. If you insist on doing it the incorrect way, you can configure your editor to hide spaces and show tabs. (Yeah, I know about PEP-8 but I don't agree with that.) – Mikko Rantalainen Oct 16 '19 at 07:45
  • these problems can be resolved depending on the ide you choose – Zina Jan 04 '21 at 09:45
  • @Zina there are certain obligations when using code editors like you can't use any other editor while doing your assignment on Coursera. – hmood Jul 10 '21 at 16:29
  • 1
    The subject has very little to do with the actual question asked. There are better phrased questions on SO, both covering `TabError` and editor configuration. Ideally this entire question should be removed, but being too old and to active that's likely not an option. How can the situation be improved so that more useful answers are presented, before these ones, to those coming for a solution to what's actually in the title? – sampi Jul 21 '22 at 05:51
  • @sampi, I think that's a [meta](https://meta.stackoverflow.com/) question, so you could ask it there (obviously first search for an existing similar answer there, maybe it has already been asked and answered). But if you think this question is a duplicate, you could simply flag it as duplicate (and/or mention the duplicate targets in a comment here). – wovano Jul 21 '22 at 05:58
  • @sampi, I do agree though that this question is not high quality. It definitely could be improved. The title is inaccurate, the code is irrelevant for the question and way too much (a [mre] would be about 3 lines, but would probably not work anyway, since the code is rendered with spaces only, so the TabError would not be reproducable when copy-pasting code from the question). But consider this question is more than 11 years old. The site rules were not as strict then as they are now. – wovano Jul 21 '22 at 08:23
  • 1
    Given the discussion, I agree that this isn't a good quality question. People who come here are going to want to understand the topic more generally, so I linked it as a duplicate to the community-driven, artificial canonical that was deliberately made to be broad enough to cover problems with indentation generally. – Karl Knechtel Jan 22 '23 at 11:09
  • That said, questions like this one absolutely would pass quality filters easily nowadays, even if they shouldn't. – Karl Knechtel Jan 22 '23 at 11:09

29 Answers29

408

Don't use tabs.

  1. Set your editor to use 4 spaces for indentation.
  2. Make a search and replace to replace all tabs with 4 spaces.
  3. Make sure your editor is set to display tabs as 8 spaces.

Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.

coolaj86
  • 74,004
  • 20
  • 105
  • 125
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • 47
    Is there any reasoning behind these dogmas? – RocketR Jul 25 '11 at 22:24
  • 7
    @RocketR: The answer is for Python. If you use tabs only, you get an 8-space indentation, unless you expand tabs to something else than 8 spaces, in which case it will look bad on other editors. If you mix tabs and spaces, it may break (see question) or look broken if you have other than 8-space expansion of tabs. In summary: Using tabs for indentation is incredibly bad. **Never do that ever** (except for languages/file formats that require it). The end. – Lennart Regebro Jul 26 '11 at 09:28
  • 2
    @RocketR Python has Pep8, a document which lists "good python style" which explicitly states that 4 spaces is the accepted form on indentation. – daniel gratzer Sep 14 '13 at 12:13
  • 7
    [Link to relevant PEP 8 section on "Tabs vs Spaces"](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) spoiler: the first line is **"Spaces are the preferred indentation method."** – Tadhg McDonald-Jensen May 12 '16 at 19:01
  • 3
    For vim: `set tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab` then `%s/\t/ /g` – Morris Jul 30 '19 at 16:03
  • 2
    If the goal is to *immediately notice* tabs, then might I suggest using a value that *isn't a multiple of* 4 spaces? Then things will visually fail to align, rather than simply being at the wrong level of indentation. – Karl Knechtel Jan 28 '22 at 10:31
  • this is wack dude – Brett Young Oct 05 '22 at 15:30
  • 1
    It is weird that [Go](https://en.wikipedia.org/wiki/Go_%28programming_language%29) went with TABs. [TABs are evil](https://www.youtube.com/watch?v=MBWAP_8zxaM&t=8m49s) – Peter Mortensen Jun 02 '23 at 12:34
211

For Visual Studio Code users

Ctrl + Shift + P or menu ViewCommand Palette.

Type:

>Convert Indentation to Spaces

Press Enter.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vivasvan Patel
  • 2,458
  • 1
  • 9
  • 14
  • 11
    If you prefer to work with Tabs, you can convert again the code by repeating the instructions above and typing instead: >Convert Indentation to Tabs – carloswm85 May 05 '21 at 15:44
150

Using the autopep8 command below fixed it for me:

 autopep8 -i my_file.py

Documentation for autopep8 linked here.

tsherwen
  • 1,076
  • 16
  • 21
Akavall
  • 82,592
  • 51
  • 207
  • 251
50

With the IDLE editor you can use this:

  • Menu EditSelect All
  • Menu FormatUntabify Region
  • Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
  • Hit select, and it fixes the entire document.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
arsb48
  • 563
  • 4
  • 10
39

When using the Sublime Text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:

Menu ViewIndentationconvert indentation to spaces

which resolved the issue for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dulangi_Kanchana
  • 1,135
  • 10
  • 21
26

It is possible to solve this problem using Notepad++ by replacing Tabs with four Spaces:

  1. Choose SearchFind... or press Ctrl + F
  2. Select the Replace tab
  3. In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
  4. In the field Find what : write \t
  5. In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
  6. Click on the button Replace All

How to replace Tabs with Spaces

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Czarek
  • 689
  • 9
  • 20
  • 1
    Note that this only works if all tabs are at the beginning of the line (so only used for _indentation_, not for _alignment_). If you used tabs at other positions, replacing them with 4 spaces will likely change your indentation in a wrong way. – wovano Jun 02 '22 at 05:29
18

Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.

Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.

On Emacs, for example, you can call the method 'untabify'.

On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):

   sed -e 's;\t;       ;' < yourFile.py > yourNedFile.py
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bruce
  • 7,094
  • 1
  • 25
  • 42
  • 2
    And if you want to do this with an open file in Vim, you can type the following: `:%s/\t/ /g` This replaces each tab character with 4 spaces. – jsaigle Nov 10 '21 at 15:02
17

If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kapilfreeman
  • 897
  • 9
  • 10
10

Sublime Text 3

In Sublime Text, while editing a Python file:

Menu FilePreferencesSettings - Syntax Specific:

File Python.sublime-settings

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chebaby
  • 7,362
  • 50
  • 46
8

I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.

BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vlad
  • 127
  • 3
  • 9
8

What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.

It worked for me...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hccavs19
  • 165
  • 3
  • 9
5

If you use Atom:

Go to Menu: PackagesWhiteSpaceConvert all Tabs to Spaces

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel Moraite
  • 422
  • 5
  • 8
3

There was a duplicate of this question from here, but I thought I would offer a view to do with modern editors and the vast array of features they offer.

With Python code, anything that needs to be indented in a .py file, needs to either all be indented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with Atom, going to preferences and then editor you can see the following two options:

Atom editor to show tabs and spaces

Then if your code is using spaces, you will see small dots where your code is indented:

Enter image description here

And if it is indented using tabs, you will see something like this:

Enter image description here

Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left. This is because of something called PEP 8, which is basically a uniform style guide for Python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples' code. It is in PEP 8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to PEP 8 warning code W191,

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alexexchanges
  • 3,252
  • 4
  • 17
  • 38
3

Try deleting the indents and then systematically either pressing Tab or pressing Space four times. This usually happens to me when I have an indent using the Tab key and then use the space key in the next line.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fateh
  • 302
  • 2
  • 12
2

I use Notepad++ and got this error.

In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.

To solve the problem, I just deleted the tab before the line then added four spaces.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3625605
  • 323
  • 1
  • 5
  • 16
2

Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:

  1. Converting tabs into spaces

    For example, if you are using Stani's Python editor you can configure it to do it on saving.

  2. Converting spaces into tabs

If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.

Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
joaquin
  • 82,968
  • 29
  • 138
  • 152
2

Solution for Sublime Text

My solution to this problem was to open it in the IDLE editor and then the IDLE editor will uncover your problem.

E.g.,

Sublime Text

while run:

    clock.tick(27)

    milli = clock.tick()
    seconds = milli/1000
    timeForLevel += seconds
    print(timeForLevel)

IDLE editor

while run:

    clock.tick(27)

       milli = clock.tick()
    seconds = milli/1000
    timeForLevel += seconds
    print(timeForLevel)

I am not saying that you should only use the IDLE editor. I'm saying that if you get that error you should check the IDLE editor.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zina
  • 159
  • 8
1

I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.

After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrushenko Alexander
  • 1,839
  • 19
  • 14
1

I oddly ran into a similar issue with one of my .py files. I simply opened the file in PyCharm and pressed Option + Command + L which correctly formats the file contents in one go.

I suspect I was having trouble because I coded this particular .py file through JupyterLab as opposed to my usual choice of Sublime Text or PyCharm and therefore ran into some hidden indentation issues many answers here have alluded to.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DrDEE
  • 506
  • 7
  • 14
1

Use Pylint. It will give you a detailed report about how many spaces you need and where.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aymen Alsaadi
  • 1,329
  • 1
  • 11
  • 12
1

The following trick has worked for me:

  1. Copy and paste the code in the Windows Notepad/Notepad++ application.
  2. Then from the Notepad/Notepad++ again select all and copy the code
  3. Paste in my views.py
  4. Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
  5. Now use the tab key again to use the proper indentation
Goldfish
  • 624
  • 6
  • 11
1

For Anaconda, Spyder users, you can go to SourceFix indentation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mr.J
  • 181
  • 1
  • 10
  • *Source* where? This is one of the [few cases](https://meta.stackoverflow.com/questions/285551/) where a screenshot does make sense. – Peter Mortensen Jun 04 '23 at 12:40
0

If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.

kozowh
  • 93
  • 2
  • 10
0

Solving this using the Vim editor:

  1. Open terminal (Ctrl + Alt + T).
  2. Go to the directory where the file is located (cd <path_to_your_directory>). Example: cd /home/vineeshvs/work.
  3. Open the file in Vim (vim <file_name>). Example: vim myfile.txt .
  4. [Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
  5. Go to the line where you have this problem (Esc :<line_number>). Ex: :53 in Vim editor after pressing Esc button once.
  6. Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Example: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing the Esc button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press Esc when you are done with the required replacements.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vineeshvs
  • 479
  • 7
  • 32
0

Well, I had the same problem and I realised that the problem is that I copied code from another Python editor to Sublime Text.

I was working with Jupyter Notebook and then I copied the code into Sublime Text. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.

So just stick to one editor. If you do so, then you won't be having any problem.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

For Jupyter users:

Ctrl + Shift + P automatically indents the selection:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohamed Fathallah
  • 1,274
  • 1
  • 15
  • 17
0

While the original question is about self authored code, the search engines lead here for when searching for the title string. It is an error message one might very likely get when attempting to make use of an already existing library or tool.

For those finding their way here when attempting to use someone else’s code: It is a Python 2 vs. Python 3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 style guide.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sampi
  • 576
  • 5
  • 15
-1

I got the same errors but could not figure out what I was doing wrong.

So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.

If anyone is wondering how I did that. Simple. Go in vim. Type in G=gg.

This will automatically fix everything. Good luck :)

-1

Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.

Another way is to use space 4 times (depending on how much you want to indent).

A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.

Hopefully, this should help.

Sarvagya Gupta
  • 861
  • 3
  • 13
  • 28