791

When I compile the Python code below, I get

IndentationError: unindent does not match any outer indentation level


import sys

def Factorial(n): # Return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

Why?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
cbrulak
  • 15,436
  • 20
  • 61
  • 101
  • 12
    I had the same error, but I happened to indent a method *way up* in the code slightly to the left, which gave this error at the bottom of the *next* method after it. So this error can occur not only from mixing tabs and spaces. – Prof. Falken Nov 02 '12 at 12:41
  • 27
    I am using Sublime Text 3. I have a Django project. I fixed the error using `View > Indentation > Intent Using Spaces` – abhimanyuaryan Mar 11 '16 at 17:08
  • 3
    I found using IDLE makes it much easier to find indentation issues. It will clearly find indentation errors that most editors wont find. – Dennis Gathagu Jan 16 '20 at 13:56
  • I am using Sublime Text 3 with a Flask project. I fixed the error using `View > Indentation > Tab Width: 4` after unselected `Indent Using Spaces`. – bmc Jun 30 '20 at 15:52
  • 2
    Sublime 3.2.2 : View > Indentation > Convert Indentation to Spaces -- worked for me – Impermanence Aug 28 '20 at 05:48
  • running ``dos2unix *`` helped in my case – meniluca May 21 '21 at 09:44
  • 2
    You can see the problem by looking at the [Markdown source](/revisions/96e24cec-7518-41c7-ba3e-362a85393b3c/view-source): You have tabs preceding the last three lines. Stack Overflow unfortunately converts tabs to 4 spaces on rendering, so the issue disappears. – wjandrea Feb 17 '22 at 03:47

32 Answers32

852

One possible cause for this error is that there might be spaces mixed with tabs for indentation. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Kevin Tighe
  • 20,181
  • 4
  • 35
  • 36
328

IMPORTANT: Spaces are the preferred method - see PEP 8 Indentation and Tabs or Spaces?. (Thanks to @Siha for this.)

For Sublime Text users:

Set Sublime Text to use tabs for indentation: View --> Indentation --> Convert Indentation to Tabs

Uncheck the Indent Using Spaces option as well in the same sub-menu above. This will immediately resolve this issue.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
psiyumm
  • 6,437
  • 3
  • 29
  • 50
  • 2
    Also whenever using Python, make sure you set a similar option in whichever IDE/Text Editor you use – psiyumm May 08 '14 at 11:46
  • 22
    Also on ATOM, Packages > Whitespace > Convert Spaces to Tabs and you will avoid a Python's Syntax Error Headache! – loretoparisi Mar 11 '15 at 14:24
  • 2
    Spaces are the preferred method - see PEP008 [Indentation](https://www.python.org/dev/peps/pep-0008/#indentation) and [Tabs or Spaces?](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces). Sublime can also be setup to do it this way round. – SiHa Jan 06 '16 at 08:00
  • 17
    you say spaces are the preferred method yet your answer asks people to ask sublime to use tabs instead! I am confused – gota Jul 07 '16 at 10:14
  • @NunoCalaim Well unfortunately, that happened after I had answered the question. If you are starting out a new project, please use the preferred technique of spaces. That is why I made an edit in bold so that any newcomers are aware of the disclaimer. – psiyumm Jul 07 '16 at 11:42
  • `cat -T yourfile.py` will help to make this easier to spot. I had a tab at the beginning of a pydoc, and was wondering what removing the pydoc removed this error for me. – Cameron Kerr Nov 15 '16 at 00:44
152

To easily check for problems with tabs/spaces you can actually do this:

python -m tabnanny yourfile.py

or you can just set up your editor correctly of course :-)

André
  • 12,971
  • 3
  • 33
  • 45
  • 1
    I tried this in a file with some tab/space indentation error, but no output at all with an incorrect tab file. any idea? – Luchux Mar 16 '12 at 03:32
  • 1
    I had a problem with spaces and the error said it was on line 191, but thanks to tabnanny I found the real problem was not on that line, but in the line above. – richar8086 Feb 28 '19 at 09:49
  • Thank you! What a great tip. Error was identified by flake8 in VS Code but it could not identify _where_ the problem was -- tabnanny did in a microsecond. – Steve Sep 26 '19 at 22:45
50

Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)

Note, it is recommended that you don't use tabs in Python code. See the style guide. You should configure Notepad++ to insert spaces for tabs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zdan
  • 28,667
  • 7
  • 60
  • 71
  • I'm confused. The answer above states to switch a text editor option to use tabs instead of spaces. – spurra Oct 08 '15 at 16:31
  • 3
    @BananaCode As long as you use ONLY tabs or ONLY spaces, it technically doesn't matter which you choose. Though for python, spaces are preferred, see the link that I referred to. – zdan Oct 08 '15 at 17:54
29

Whenever I've encountered this error, it's because I've somehow mixed up tabs and spaces in my editor.

Dana
  • 32,083
  • 17
  • 62
  • 73
22

If you are using Vim, hit escape and then type

gg=G

This auto indents everything and will clear up any spaces you have thrown in.

cbartondock
  • 663
  • 6
  • 17
18

If you use Python's IDLE editor you can do as it suggests in one of similar error messages:

1) select all, e.g. Ctrl + A

2) Go to Format -> Untabify Region

3) Double check your indenting is still correct, save and rerun your program.

I'm using Python 2.5.4

Tshilidzi Mudau
  • 7,373
  • 6
  • 36
  • 49
Gatica
  • 593
  • 1
  • 6
  • 13
11

The line: result = result * i should be indented (it is the body of the for-loop).

Or - you have mixed space and tab characters

Abgan
  • 3,696
  • 22
  • 31
  • I had to change the editing in SO, strange. See my updated "Edit" note in the question – cbrulak Jan 29 '09 at 16:41
  • Ok, so I believe that second line of my answer is correct - you have mixed space and tab characters (32 and 8 in ASCII, respectively) – Abgan Jan 29 '09 at 16:44
11

For Spyder users goto Source > Fix Indentation to fix the issue immediately

Abdulbasith
  • 139
  • 1
  • 8
11

Using Visual studio code

If you are using vs code than, it will convert all mix Indentation to either space or tabs using this simple steps below.

  1. press Ctrl + Shift + p

  2. type indent using spaces

  3. Press Enter

Devil
  • 1,054
  • 12
  • 18
10

On Atom

go to

Packages > Whitespace > Convert Spaces to Tabs

Then check again your file indentation:

python -m tabnanny yourFile.py

or

>python
>>> help("yourFile.py")
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
9

If you use notepad++, do a "replace" with extended search mode to find \t and replace with four spaces.

Jackie Lee
  • 239
  • 3
  • 3
9

If you use colab, then you can do avoid the error by this commands.

  1. < Ctrl-A >
  2. < Tab >
  3. < Shift-Tab >

It's all [tab] indentation convert to [space] indentation. Then OK.

WangSung
  • 259
  • 2
  • 5
8

Looks to be an indentation problem. You don't have to match curly brackets in Python but you do have to match indentation levels.

The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.

Also, injecting copy-pasted code is a common source for this type of problem.

Matt Kahl
  • 763
  • 7
  • 9
6

For what its worth, my docstring was indented too much and this also throws the same error

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

IndentationError: unindent does not match any outer indentation level

plfrick
  • 1,109
  • 12
  • 12
6

I'm using Sublime text in Ubuntu OS. To fix this issue go to

view -> Indentation -> convert indentation to tabs

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rahal Kanishka
  • 720
  • 13
  • 27
4

Just a addition. I had a similar problem with the both indentations in Notepad++.

  1. Unexcepted indentation
  2. Outer Indentation Level

    Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \t with four spaces

    Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \n with nothing

4

I was using Jupyter notebook and tried almost all of the above solutions (adapting to my scenario) to no use. I then went line by line, deleted all spaces for each line and replaced with tab. That solved the issue.

Cur123
  • 89
  • 1
  • 8
3

It could be because the function above it is not indented the same way. i.e.

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")
Ali
  • 31
  • 1
2

Since I realize there's no answer specific to spyder,I'll add one: Basically, carefully look at your if statement and make sure all if, elif and else have the same spacing that is they're in the same line at the start like so:

def your_choice(answer):
    if answer>5:
        print("You're overaged")
    elif answer<=5 and answer>1: 
            print("Welcome to the toddler's club!")
    else:
            print("No worries mate!")
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
2

I am using Sublime Text 3 with a Flask project. I fixed the error using View > Indentation > Tab Width: 4 after unselected Indent Using Spaces

bmc
  • 817
  • 1
  • 12
  • 23
1

This is because there is a mix-up of both tabs and spaces. You can either remove all the spaces and replace them with tabs.

Or, Try writing this:

#!/usr/bin/python -tt

at the beginning of the code. This line resolves any differences between tabs and spaces.

Eragon
  • 11
  • 1
1

for Atom Users, Packages ->whitspace -> remove trailing whitespaces this worked for me

Aha
  • 134
  • 8
1

I had a function defined, but it did not had any content apart from its function comments...

def foo(bar):
    # Some awesome temporary comment.
    # But there is actually nothing in the function!
    # D'Oh!

It yelled :

  File "foobar.py", line 69

                                ^
IndentationError: expected an indented block

(note that the line the ^ mark points to is empty)

--

Multiple solutions:

1: Just comment out the function

2: Add function comment

def foo(bar):
    '' Some awesome comment. This comment could be just one space.''

3: Add line that does nothing

def foo(bar):
    0

In any case, make sure to make it obvious why it is an empty function - for yourself, or for your peers that will use your code

Cedric
  • 5,135
  • 11
  • 42
  • 61
1

Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.

Secondly you can write it like this:

import sys

def Factorial(n): # Return factorial
  result = 0
  for i in range (1,n):
     result = result * i

  print "factorial is ",result
  return result

Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.

1

For example:

1. def convert_distance(miles):
2.   km = miles * 1.6
3.   return km

In this code same situation occurred for me. Just delete the previous indent spaces of line 2 and 3, and then either use tab or space. Never use both. Give proper indentation while writing code in python. For Spyder goto Source > Fix Indentation. Same goes to VC Code and sublime text or any other editor. Fix the indentation.

Ayush Aryan
  • 201
  • 4
  • 4
1

I got this error even though I didn't have any tabs in my code, and the reason was there was a superfluous closing parenthesis somewhere in my code. I should have figured this out earlier because it was messing up spaces before and after some equal signs... If you find anything off even after running Reformat code in your IDE (or manually running autopep8), make sure all your parentheses match, starting backwards from the weird spaces before/after the first equals sign.

Bartleby
  • 1,144
  • 1
  • 13
  • 14
1

Another way of correcting the indentation error is to copy your code to PyCharm if you have configured that already and reformat the file it will automatically indent correctly.

0

I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.

0

I had the same error because of another thing, it was not about tabs vs. spaces. I had the first if slightly more indented than an else: much further down. If it is just about a space or two, you might oversee it after a long code block. Same thing with docstrings:

"""comment comment 
comment
"""

They also need to be aligned, see the other answer on the same page here.

Reproducible with a few lines:

if a==1:
    print('test')
 else:
    print('test2')

Throws:

  File "<ipython-input-127-52bbac35ad7d>", line 3
    else:
         ^
IndentationError: unindent does not match any outer indentation level
questionto42
  • 7,175
  • 4
  • 57
  • 90
0

I actually get this in pylint from a bracket in the wrong place.

I'm adding this answer because I sent a lot of time looking for tabs. In this case, it has nothing to do with tabs or spaces.

    def some_instance_function(self):

        json_response = self.some_other_function()

        def compare_result(json_str, variable):
            """
            Sub function for comparison
            """
            json_value = self.json_response.get(json_str, f"{json_str} not found")

            if str(json_value) != str(variable):
                logging.error("Error message: %s, %s", 
                    json_value,
                    variable) # <-- Putting the bracket here causes the error below
                    #) <-- Moving the bracket here fixes the issue
                return False
            return True

        logging.debug("Response: %s", self.json_response)
        #        ^----The pylint error reports here 
SpiRail
  • 1,377
  • 19
  • 28
0

I got the similar error below:

IndentationError: expected an indented block

When I forgot to put pass to the class or function below, then other code was written after the class or function as shown below:

class Person:
    # pass

x = 10
def test():
    # pass

x = 10

And, when other code was not written after the class or function as shown below:

class Person:
    # pass

# x = 10
def test():
    # pass

# x = 10

I got the error below:

SyntaxError: unexpected EOF while parsing

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129