IndentationError: unindent does not match any outer indentation level

PythonIndentation

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Other posters are probably correct...there might be spaces mixed in with your tabs. 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)

Solution 2 - Python

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.

Solution 3 - Python

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 :-)

Solution 4 - Python

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.

Solution 5 - Python

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

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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

Or - you have mixed space and tab characters

Solution 9 - Python

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

Solution 10 - Python

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")

Solution 11 - Python

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

Solution 12 - Python

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

Solution 13 - Python

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.

Solution 14 - Python

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

Solution 15 - Python

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.

Solution 16 - Python

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

Solution 17 - Python

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

> view -> Indentation -> convert indentation to tabs

Solution 18 - Python

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.

Solution 19 - Python

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")

Solution 20 - Python

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

Solution 21 - Python

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!")

Solution 22 - Python

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

Solution 23 - Python

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.

Solution 24 - Python

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.

Solution 25 - Python

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

Solution 26 - Python

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.

Solution 27 - Python

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.

Solution 28 - Python

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.

Solution 29 - Python

in my case, the problem was the configuration of pydev on Eclipse

pydev @ Eclipse

Solution 30 - Python

If you use Komodo editor you can do as it suggests in one of similar error messages:

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

  2. Go to Code -> Untabify Region

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

I'm using Python 3.4.2

Solution 31 - Python

If you are using Sublime text for python development,you can avoid the error by using the package Anaconda.After installing Anaconda,

> 1. open your file in sublime > 2. right click on the open spaces > 3. choose anaconda > 4. click on autoformat > 5. DONE Or Press CTRL+ALT+R.

Solution 32 - Python

In intellij with python plugin, Ctrl + Shift + Alt to reformat the document fixed the indent/tab/spaces problem

Solution 33 - Python

For SPYDER users: I'm using spyder 3.3.2 with python 3.7.1 and I solved this, setting indentation to use tabs, with the following steps, click on:

  • Tools.
  • Preferences.
  • Editor.
  • Advanced settings.
  • Indentation characters -> Tabs.

Then I reset the "unidented" line using tab key.

For some reason, without this setting, I got the ghost IndentationError sometimes.

Solution 34 - Python

Try opening the file with another editor and check if there is any issue with the way the lines are organized.

Solution 35 - Python

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

Solution 36 - Python

I ran into this problem today and didn't see the mistake I made listed so I thought I'd add it - and maybe save someone else a few hours :)

I use carriage returns in my functions and in this case the blank line wasn't properly indented. That caused Python to throw this error and exit.

Solution 37 - Python

This happens mainly because of editor .Try changing tabs to spaces(4).the best python friendly IDE or Editors are pycharm ,sublime ,vim for linux.
even i too had encountered the same issue , later i found that there is a encoding issue .i suggest u too change ur editor.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncbrulakView Question on Stackoverflow
Solution 1 - PythonKevin TigheView Answer on Stackoverflow
Solution 2 - PythonactivatedgeekView Answer on Stackoverflow
Solution 3 - PythonAndréView Answer on Stackoverflow
Solution 4 - PythonzdanView Answer on Stackoverflow
Solution 5 - PythonDanaView Answer on Stackoverflow
Solution 6 - PythoncbartondockView Answer on Stackoverflow
Solution 7 - PythonGaticaView Answer on Stackoverflow
Solution 8 - PythonAbganView Answer on Stackoverflow
Solution 9 - PythonAbdulbasithView Answer on Stackoverflow
Solution 10 - PythonloretoparisiView Answer on Stackoverflow
Solution 11 - PythonDevilView Answer on Stackoverflow
Solution 12 - PythonJackie LeeView Answer on Stackoverflow
Solution 13 - PythonMatt KahlView Answer on Stackoverflow
Solution 14 - Pythonuser4398985View Answer on Stackoverflow
Solution 15 - PythonCur123View Answer on Stackoverflow
Solution 16 - PythonplfrickView Answer on Stackoverflow
Solution 17 - PythonRahal KanishkaView Answer on Stackoverflow
Solution 18 - PythonWangSungView Answer on Stackoverflow
Solution 19 - PythonAliView Answer on Stackoverflow
Solution 20 - PythonAhaView Answer on Stackoverflow
Solution 21 - PythonNelsonGonView Answer on Stackoverflow
Solution 22 - PythonbmcView Answer on Stackoverflow
Solution 23 - PythonEragonView Answer on Stackoverflow
Solution 24 - Pythonuser3731311View Answer on Stackoverflow
Solution 25 - PythonCedricView Answer on Stackoverflow
Solution 26 - PythonFaisal Ahmed FarooqView Answer on Stackoverflow
Solution 27 - PythonAyush AryanView Answer on Stackoverflow
Solution 28 - PythonBartlebyView Answer on Stackoverflow
Solution 29 - PythonRui MartinsView Answer on Stackoverflow
Solution 30 - PythonImtiaz PabelView Answer on Stackoverflow
Solution 31 - PythonKapilfreemanView Answer on Stackoverflow
Solution 32 - PythonRene FergusonView Answer on Stackoverflow
Solution 33 - PythonMikeView Answer on Stackoverflow
Solution 34 - Pythonalbus_cView Answer on Stackoverflow
Solution 35 - Pythonquestionto42standswithUkraineView Answer on Stackoverflow
Solution 36 - PythonHoturuView Answer on Stackoverflow
Solution 37 - PythonyunusView Answer on Stackoverflow