Unindent does not match any outer indentation level python как исправить

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 rang...

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?

Martijn Pieters's user avatar

asked Jan 29, 2009 at 16:34

cbrulak's user avatar

7

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)

Machavity's user avatar

Machavity

30.5k27 gold badges90 silver badges100 bronze badges

answered Jan 29, 2009 at 16:37

Kevin Tighe's user avatar

Kevin TigheKevin Tighe

19.7k4 gold badges35 silver badges36 bronze badges

8

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's user avatar

wjandrea

26.2k8 gold badges57 silver badges78 bronze badges

answered May 8, 2014 at 11:44

activatedgeek's user avatar

activatedgeekactivatedgeek

6,3593 gold badges28 silver badges50 bronze badges

6

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

answered Feb 4, 2009 at 21:50

André's user avatar

AndréAndré

12.9k3 gold badges33 silver badges45 bronze badges

3

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's user avatar

answered Jan 29, 2009 at 16:41

zdan's user avatar

zdanzdan

28.2k7 gold badges59 silver badges68 bronze badges

2

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

answered Jan 29, 2009 at 16:45

Dana's user avatar

DanaDana

31.6k17 gold badges62 silver badges72 bronze badges

0

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.

answered May 7, 2015 at 9:43

cbartondock's user avatar

cbartondockcbartondock

6446 silver badges17 bronze badges

0

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's user avatar

answered Jun 13, 2013 at 15:26

Gatica's user avatar

GaticaGatica

5931 gold badge6 silver badges13 bronze badges

0

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

Or — you have mixed space and tab characters

answered Jan 29, 2009 at 16:38

Abgan's user avatar

AbganAbgan

3,68022 silver badges31 bronze badges

2

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

answered Jan 5, 2020 at 16:56

Abdulbasith's user avatar

0

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

answered Jul 24, 2020 at 8:01

Devil's user avatar

DevilDevil

97211 silver badges17 bronze badges

1

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

answered Mar 11, 2015 at 14:27

loretoparisi's user avatar

loretoparisiloretoparisi

15.3k11 gold badges98 silver badges138 bronze badges

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

answered Mar 20, 2014 at 17:23

Jackie Lee's user avatar

Jackie LeeJackie Lee

2393 silver badges3 bronze badges

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.

answered Jul 31, 2012 at 20:27

Matt Kahl's user avatar

Matt KahlMatt Kahl

7337 silver badges9 bronze badges

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.

answered Nov 25, 2021 at 3:40

WangSung's user avatar

WangSungWangSung

1992 silver badges5 bronze badges

0

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

answered Nov 12, 2015 at 21:42

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.

answered Dec 15, 2018 at 4:48

Cur123's user avatar

Cur123Cur123

911 silver badge8 bronze badges

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

answered Mar 5, 2019 at 23:00

plfrick's user avatar

plfrickplfrick

1,05912 silver badges12 bronze badges

1

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

view -> Indentation -> convert indentation to tabs

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Mar 3, 2021 at 10:28

Rahal Kanishka's user avatar

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

answered Feb 14, 2014 at 2:52

Ali's user avatar

0

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

answered Dec 7, 2018 at 13:42

NelsonGon's user avatar

NelsonGonNelsonGon

12.9k6 gold badges27 silver badges57 bronze badges

0

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

answered Jun 30, 2020 at 15:52

bmc's user avatar

bmcbmc

8171 gold badge12 silver badges20 bronze badges

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.

answered Mar 5, 2014 at 13:43

Eragon's user avatar

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.

answered Jun 26, 2014 at 15:57

user3731311's user avatar

0

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

answered Jul 28, 2015 at 12:41

Aha's user avatar

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

answered Dec 10, 2018 at 14:07

Cedric's user avatar

CedricCedric

5,02511 gold badges40 silver badges59 bronze badges

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.

answered Dec 25, 2018 at 11:49

Faisal Ahmed Farooq's user avatar

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.

answered Apr 11, 2020 at 6:48

Ayush Aryan's user avatar

Ayush AryanAyush Aryan

1913 silver badges4 bronze badges

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.

answered Jul 24, 2020 at 7:52

Bartleby's user avatar

BartlebyBartleby

9551 gold badge12 silver badges14 bronze badges

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

answered Oct 1, 2021 at 14:19

questionto42's user avatar

questionto42questionto42

5,7713 gold badges44 silver badges73 bronze badges

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 

answered Oct 11, 2022 at 10:13

SpiRail's user avatar

SpiRailSpiRail

1,36719 silver badges28 bronze badges

1

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?

Martijn Pieters's user avatar

asked Jan 29, 2009 at 16:34

cbrulak's user avatar

7

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)

Machavity's user avatar

Machavity

30.5k27 gold badges90 silver badges100 bronze badges

answered Jan 29, 2009 at 16:37

Kevin Tighe's user avatar

Kevin TigheKevin Tighe

19.7k4 gold badges35 silver badges36 bronze badges

8

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's user avatar

wjandrea

26.2k8 gold badges57 silver badges78 bronze badges

answered May 8, 2014 at 11:44

activatedgeek's user avatar

activatedgeekactivatedgeek

6,3593 gold badges28 silver badges50 bronze badges

6

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

answered Feb 4, 2009 at 21:50

André's user avatar

AndréAndré

12.9k3 gold badges33 silver badges45 bronze badges

3

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's user avatar

answered Jan 29, 2009 at 16:41

zdan's user avatar

zdanzdan

28.2k7 gold badges59 silver badges68 bronze badges

2

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

answered Jan 29, 2009 at 16:45

Dana's user avatar

DanaDana

31.6k17 gold badges62 silver badges72 bronze badges

0

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.

answered May 7, 2015 at 9:43

cbartondock's user avatar

cbartondockcbartondock

6446 silver badges17 bronze badges

0

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's user avatar

answered Jun 13, 2013 at 15:26

Gatica's user avatar

GaticaGatica

5931 gold badge6 silver badges13 bronze badges

0

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

Or — you have mixed space and tab characters

answered Jan 29, 2009 at 16:38

Abgan's user avatar

AbganAbgan

3,68022 silver badges31 bronze badges

2

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

answered Jan 5, 2020 at 16:56

Abdulbasith's user avatar

0

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

answered Jul 24, 2020 at 8:01

Devil's user avatar

DevilDevil

97211 silver badges17 bronze badges

1

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

answered Mar 11, 2015 at 14:27

loretoparisi's user avatar

loretoparisiloretoparisi

15.3k11 gold badges98 silver badges138 bronze badges

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

answered Mar 20, 2014 at 17:23

Jackie Lee's user avatar

Jackie LeeJackie Lee

2393 silver badges3 bronze badges

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.

answered Jul 31, 2012 at 20:27

Matt Kahl's user avatar

Matt KahlMatt Kahl

7337 silver badges9 bronze badges

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.

answered Nov 25, 2021 at 3:40

WangSung's user avatar

WangSungWangSung

1992 silver badges5 bronze badges

0

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

answered Nov 12, 2015 at 21:42

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.

answered Dec 15, 2018 at 4:48

Cur123's user avatar

Cur123Cur123

911 silver badge8 bronze badges

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

answered Mar 5, 2019 at 23:00

plfrick's user avatar

plfrickplfrick

1,05912 silver badges12 bronze badges

1

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

view -> Indentation -> convert indentation to tabs

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Mar 3, 2021 at 10:28

Rahal Kanishka's user avatar

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

answered Feb 14, 2014 at 2:52

Ali's user avatar

0

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

answered Dec 7, 2018 at 13:42

NelsonGon's user avatar

NelsonGonNelsonGon

12.9k6 gold badges27 silver badges57 bronze badges

0

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

answered Jun 30, 2020 at 15:52

bmc's user avatar

bmcbmc

8171 gold badge12 silver badges20 bronze badges

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.

answered Mar 5, 2014 at 13:43

Eragon's user avatar

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.

answered Jun 26, 2014 at 15:57

user3731311's user avatar

0

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

answered Jul 28, 2015 at 12:41

Aha's user avatar

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

answered Dec 10, 2018 at 14:07

Cedric's user avatar

CedricCedric

5,02511 gold badges40 silver badges59 bronze badges

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.

answered Dec 25, 2018 at 11:49

Faisal Ahmed Farooq's user avatar

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.

answered Apr 11, 2020 at 6:48

Ayush Aryan's user avatar

Ayush AryanAyush Aryan

1913 silver badges4 bronze badges

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.

answered Jul 24, 2020 at 7:52

Bartleby's user avatar

BartlebyBartleby

9551 gold badge12 silver badges14 bronze badges

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

answered Oct 1, 2021 at 14:19

questionto42's user avatar

questionto42questionto42

5,7713 gold badges44 silver badges73 bronze badges

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 

answered Oct 11, 2022 at 10:13

SpiRail's user avatar

SpiRailSpiRail

1,36719 silver badges28 bronze badges

1

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?

Martijn Pieters's user avatar

asked Jan 29, 2009 at 16:34

cbrulak's user avatar

7

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)

Machavity's user avatar

Machavity

30.5k27 gold badges90 silver badges100 bronze badges

answered Jan 29, 2009 at 16:37

Kevin Tighe's user avatar

Kevin TigheKevin Tighe

19.7k4 gold badges35 silver badges36 bronze badges

8

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's user avatar

wjandrea

26.2k8 gold badges57 silver badges78 bronze badges

answered May 8, 2014 at 11:44

activatedgeek's user avatar

activatedgeekactivatedgeek

6,3593 gold badges28 silver badges50 bronze badges

6

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

answered Feb 4, 2009 at 21:50

André's user avatar

AndréAndré

12.9k3 gold badges33 silver badges45 bronze badges

3

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's user avatar

answered Jan 29, 2009 at 16:41

zdan's user avatar

zdanzdan

28.2k7 gold badges59 silver badges68 bronze badges

2

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

answered Jan 29, 2009 at 16:45

Dana's user avatar

DanaDana

31.6k17 gold badges62 silver badges72 bronze badges

0

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.

answered May 7, 2015 at 9:43

cbartondock's user avatar

cbartondockcbartondock

6446 silver badges17 bronze badges

0

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's user avatar

answered Jun 13, 2013 at 15:26

Gatica's user avatar

GaticaGatica

5931 gold badge6 silver badges13 bronze badges

0

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

Or — you have mixed space and tab characters

answered Jan 29, 2009 at 16:38

Abgan's user avatar

AbganAbgan

3,68022 silver badges31 bronze badges

2

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

answered Jan 5, 2020 at 16:56

Abdulbasith's user avatar

0

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

answered Jul 24, 2020 at 8:01

Devil's user avatar

DevilDevil

97211 silver badges17 bronze badges

1

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

answered Mar 11, 2015 at 14:27

loretoparisi's user avatar

loretoparisiloretoparisi

15.3k11 gold badges98 silver badges138 bronze badges

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

answered Mar 20, 2014 at 17:23

Jackie Lee's user avatar

Jackie LeeJackie Lee

2393 silver badges3 bronze badges

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.

answered Jul 31, 2012 at 20:27

Matt Kahl's user avatar

Matt KahlMatt Kahl

7337 silver badges9 bronze badges

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.

answered Nov 25, 2021 at 3:40

WangSung's user avatar

WangSungWangSung

1992 silver badges5 bronze badges

0

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

answered Nov 12, 2015 at 21:42

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.

answered Dec 15, 2018 at 4:48

Cur123's user avatar

Cur123Cur123

911 silver badge8 bronze badges

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

answered Mar 5, 2019 at 23:00

plfrick's user avatar

plfrickplfrick

1,05912 silver badges12 bronze badges

1

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

view -> Indentation -> convert indentation to tabs

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Mar 3, 2021 at 10:28

Rahal Kanishka's user avatar

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

answered Feb 14, 2014 at 2:52

Ali's user avatar

0

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

answered Dec 7, 2018 at 13:42

NelsonGon's user avatar

NelsonGonNelsonGon

12.9k6 gold badges27 silver badges57 bronze badges

0

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

answered Jun 30, 2020 at 15:52

bmc's user avatar

bmcbmc

8171 gold badge12 silver badges20 bronze badges

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.

answered Mar 5, 2014 at 13:43

Eragon's user avatar

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.

answered Jun 26, 2014 at 15:57

user3731311's user avatar

0

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

answered Jul 28, 2015 at 12:41

Aha's user avatar

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

answered Dec 10, 2018 at 14:07

Cedric's user avatar

CedricCedric

5,02511 gold badges40 silver badges59 bronze badges

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.

answered Dec 25, 2018 at 11:49

Faisal Ahmed Farooq's user avatar

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.

answered Apr 11, 2020 at 6:48

Ayush Aryan's user avatar

Ayush AryanAyush Aryan

1913 silver badges4 bronze badges

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.

answered Jul 24, 2020 at 7:52

Bartleby's user avatar

BartlebyBartleby

9551 gold badge12 silver badges14 bronze badges

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

answered Oct 1, 2021 at 14:19

questionto42's user avatar

questionto42questionto42

5,7713 gold badges44 silver badges73 bronze badges

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 

answered Oct 11, 2022 at 10:13

SpiRail's user avatar

SpiRailSpiRail

1,36719 silver badges28 bronze badges

1

Вот код:

import pygame
import sys

pygame.init()
win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("ParaaCherzz")

x = 50
y = 425
width = 40
height = 60
speed = 5

isJump = False
jumpCount = 10

run = True
while run:
  pygame.time.delay(50)

  for event in pygame.event.get():
      if event.type == pygame.QUIT:
        run = False
        sys.exit()
  if event.type == pygame.KEYDOWN:
     if event.key == pygame.K_LEFT and x > 5:
         x -= speed
     if event.key == pygame.K_RIGHT and   x < 500 - width - 5:
         x += speed
  if not(isJump):
     if event.key == pygame.K_UP and y > 5:
         y -= speed
     if event.key == pygame.K_DOWN and y < 500 - height -15:
         y += speed
     if event.key == pygame.K_SPACE:
         isJump = True
  else:
      if jumpCount >= -10:
          if jumpCount < 0:
         y += (jumpCount ** 2) / 2
     else:
         y -= (jumpCount ** 2) / 2
        jumpCount -= 1
    else:
      isJump = False
      jumpCount = 10

  win.fill((0,0,0))
  pygame.draw.rect(win, (0,0,255), (x, y, width, height))
  pygame.display.update()

pygame.quit()

Когда пытаюсь запустить, ошибка в строке 41 (y += (jumpCount ** 2) / 2):

IndentationError: unindent does not match any outer indentation level

Как исправить?


  • Вопрос задан

    более года назад

  • 15663 просмотра

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

Да отступы свои исправьте!
Мало того, что в коде они у вас не верны, о чем вам интерпретатор явно говорит, так и сюда тыкаете код вообще без отсупов. В Python отступы — это все, неужели на первом занятии вам об этом не сказали???
И да, английским займитесь. Слово «indentation» так и переводится — «отступ».

Перепроверьте сколько пробклов в каждой строчке. Нет ли там табов?

В питоне нет фигурных скобок, как в си, или begin/end, как в паскале. Содержимое блока (if/for) выделяется отступом.


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

12 февр. 2023, в 22:43

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

09 февр. 2023, в 13:28

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

12 февр. 2023, в 21:32

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

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

Indentation is important for making your code look well-structured and clean. This will help you to separate the code into multiple blocks and make it more readable. In languages such as C or C++, curly braces {} are used.

Improper indentation in Python raises an error called “unindent does not match any outer indentation level”. In this post, we will figure out the ways to solve this problem.

But first, let us learn about indentation in Python.      

What is Indentation in Python?

In Python, indentation is the space or tab that programmers put at the beginning of every line. In Python, whitespace is used for indenting the code. Code is indented from left to right.

In python, we don’t use indention just for the beautification of code or to make the code look pretty. When you do indent using one space or two space for the first line, it must be same for the rest of the lines. 

In the picture shown below, you can see there are three blocks of code, and each block code has an identical indentation. 

What is Indentation

What is ‘IndentationError: unindent does not match any outer indentation level’?

This type of error occurs when we assign extra indent to an identical code block. Due to this additional indent, the python compiler is not able to recognize similar code blocks, and it throws an error. To fix this, you have to make sure all blocks of similar code have the same indentation.

IndentationError: Unindent does not match any outer indentation level

Let us look at some examples to understand the error and its solution.

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:

File "t.py", line 7
    else:
        ^
IndentationError: unindent does not match any outer indentation level

In the above code example “if” and “elif” statements are assigned with no indent whereas “else” statement (see line no 7) which is belong to “if” statement, assigned with an extra indent. Due to an additional indent python compiler was not able to recognize “else” statement (line no 7) and throw the indentation error ’unindent does not match any outer indentation level’.

Correct Code:

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

Therefore, before compiling the code, check the overall indentation to avoid the “unindent does not match any outer indentation level” error. 

Python uses indentation to define the scope and extent of code blocks in constructs like class, function, conditional statements and loops. You can use both spaces and tabs to indent your code, and if you use both methods when writing your code, you will raise the error: IndentationError: unindent does not match any outer indentation level.

We will go through the error in detail and an example to learn how to solve it.


Table of contents

  • IndentationError: unindent does not match any outer indentation level
    • What is Indentation in Python?
  • Example: Mixing Indentation in Function
    • Solution
  • Summary

IndentationError: unindent does not match any outer indentation level

What is Indentation in Python?

Indentation is vital for constructing programs in Python. It refers to the correct use of white space to start a code block. With indentations, we can quickly identify the beginning and endpoint of any code block in our program. Let’s look at how indentation in Python works visually:

code indentation in Python
Code indentation in Python

To indicate a code block in Python, you must indent each block line by the same amount. You can use four spaces or one tab, a typical indentation for Python. According to the conventions in PEP 8, four white spaces is preferable. You can use indentation to nest code blocks within code blocks.

Python objects if you use both spaces and tabs to indent your code. You need to use one form of indentation, and this can be tricky because you cannot see the difference between spaces and tabs.

The error commonly occurs when you copy code from other sources to your script. The code you are copying may have a different indentation to what you are using.

The error can also occur if you have used indentation in the wrong place or have not used any indentation.

Example: Mixing Indentation in Function

Let’s write a program that calculates the square roots of a list of numbers and prints the result to the console. We will start by defining the function to calculate the square root of a number:

def get_square_roots(number_list):

    for number in number_list:

        sqrt_number = number ** 0.5

	    print(f'The square root of {number} is {sqrt_number}')

The function uses a for loop to iterate through every number in the list you will pass. We use the exponentiation operator to calculate the square root of the number and then print the result. Next, we will define the list of numbers and then call the get_square_roots() function.

number_list = [4, 9, 16, 25, 36]

get_square_roots(number_list)

Let’s run the code and see what happens:

sqrt_number = number ** 0.5
                          ^
IndentationError: unindent does not match any outer indentation level

The code returns the IndentationError, and the tick indicates the line responsible for the error.

Solution

We can use a text editor like Sublime Text to see the indentation style in our code by highlighting it, as shown below.

Code block with mixed indentation style
Code block with mixed indentation style

Each line represents a tab, and a dot represents a space. We can see a mix of spaces and tabs in the code snippet, particularly the line sqrt_number = number ** 0.5. To fix this, you can change replace the indentation on the other lines with four white spaces as this is the preferred indentation method. Alternatively, you can use tabs. Let’s look at the revised code in the text editor:

Code block with consistent indentation style
Code block with consistent indentation style

We can see each line has spaces instead of tabs. Let’s run the code to see what happens:

The square root of 4 is 2.0
The square root of 9 is 3.0
The square root of 16 is 4.0
The square root of 25 is 5.0
The square root of 36 is 6.0

The program returns the square root of each number in the list we pass to the function. You do not need to use a text editor to find differences in indentation style, but it does make it easier to spot them. Alternatively, you can manually go through each line in your code and stick to one indentation style.

Summary

Congratulations on reading to the end of this tutorial! The error “indentationerror: unindent does not match any outer indentation level” occurs when you mix spaces and tabs to indent your code. To solve this error, ensure all your code uses either spaces or tabs in your program. You can use a text editor to highlight your code to make it easier to spot the differences. Otherwise, you can go over the lines in your code and stick to one indentation style. To minimise the likelihood of this error, you can write your code in a text editor or Integrated Development Environment (IDE) like PyCharm, which automatically indent your code in a consistent style.

For further reading on Python code structure, go to the article: How to Solve Python UnboundLocalError: local variable referenced before assignment.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Table of Contents
Hide
  1. What is Indentation in Python?
  2. Tabs or Spaces?
  3. Fix indentationerror: unindent does not match any outer indentation level
    1. A mix of Spaces and Tabs
    2. Mismatch of Indent size inside a code block
    3. Wrong indentation or mismatch of a code block

Indentation in Python is important, and it makes your code well structured and clean. Python uses indentation to define code blocks. You can use either tabs or spaces to indent the code. However, using a combination of space and tab will result in indentationerror: unindent does not match any outer indentation level.

What is Indentation in Python?

In Python, indentation is done using whitespace. In simple terms, indentation refers to adding white space before a statement. According to the PEP 8 rule, the standard way to indent the code is to use 4 spaces per indent level.

Without indentation Python will not know which code to execute next or which statement belongs to which block and will lead to IndentationError.

Tabs or Spaces?

The best practice is to use spaces as the indentation, and the same is the preferred indentation by the PEP 8 rule.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Mixing tabs and spaces is not allowed, and if you do that, Python will throw indentationerror: unindent does not match any outer indentation level, and the compilation of the code will fail.

Let’s take few examples and find out the possible cause and solution for indentationerros in Python.

A mix of Spaces and Tabs

This would be a common scenario where the developers tend to make mistakes by mixing both spaces and tabs. Follow one approach consistently, either tab or space, to resolve the error but never use a mix of both.

Example 

a=5
b=10

if a<b:
    print("Using 4 space for indentation")
    print("using tab for indentation")

Output

  File "c:ProjectsTryoutslistindexerror.py", line 6
    print("using tab for indentation")
IndentationError: unexpected indent

Suppose you are using code editors like VS Code and Pycharm. In that case, it will automatically resolve the issue by converting from tabs to spaces or spaces to tab, depending on the IDE configuration settings. However, if you are using any other editor like notepad++ or sublime or using the command line for writing code, you may face this issue often, and the solution is to use one consistent approach.

Mismatch of Indent size inside a code block

If you are using any statements, loops, and functions, the code block inside should have the same indentation level. Otherwise, you wil get an IndentationError.

Example 

number=6
for i in range(1,number):
    print (i)
        print(number)

Output

 File "c:ProjectsTryoutslistindexerror.py", line 4
    print(number)
IndentationError: unexpected indent

Solution

number=6
for i in range(1,number):
    print (i)
    print(number)

Wrong indentation or mismatch of a code block

Often in larger projects, the number of lines will be more, leading to a mismatch of code blocks while writing loops, statements, and functions.

A typical use case is an if-else statement where due to a large no of lines the, if block and else block indentation may differ, which leads to indentationerror: unindent does not match any outer indentation level.

Example

a=5
b=6

if a< b:
        print("a is smaller")
    else:
        print("b is smaller")

Output

  File "c:ProjectsTryoutslistindexerror.py", line 6
    else:
         ^
IndentationError: unindent does not match any outer indentation level

Solution

a=5
b=6

if a< b:
        print("a is smaller")
else:
        print("b is smaller")

Output

a is smaller

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.

In this post, we’ll provide 5+ fixes for the frustrating Indentation Error: unindent does not match any outer indentation level error.

One of the common errors in programming is the indentation error. It happens when unindent does not match any outer indentation level, but what is this error all about and how to fix it? Before we define what indentation is and why this error occurs, let us identify how programs work.

Each computer program has its own coding style guidelines. In programming, there is a set of standards used in writing the source code for a specific computer program. They are known as the code lay-out or the programming style. It helps the programmers read and understand a particular source code whose function is to prevent initiating errors.

And this error can really piss people off

WHAT THE ACTUAL F IT SHOULD WORK BUT NOOOO

«compile error: unindent does not match any outer indentation level»

AYOKO NA

— solanaceae (@lc_potato) September 27, 2017

In programming, code lay-out is designed for a specific programming language.

Programming languages are letters taken from the alphabet that is formed in accordance with a particular set of rules. This is where indentation comes in. Programming languages use indentation to determine the limits of logical blocks of code. If codes are indented, codes are more eye-friendly. In other words, they will be readable. On the other hand, the indentation in Python is required to indicate which blocks of code a statement belongs to.

Indentation uses four spaces per indentation level. This is where indentation error usually takes place. This is where unindent does not match any outer indentation level. Mixing spaces with tabs is what causes the error.

Also, other factors that affect the alignment of the elements may cause the system to respond differently. There are guidelines, fixes, and preventive measures for this issue below.

But first- check out some more reaction from social media regarding this annoying error: 

It also gives you a diagnostic error right when you run the code:

IndentationError: unindent does not match any outer indentation level.

— 🖥️🏳️‍🌈unsafe fn bot() ➡️ impl CRJ Shitposting (@KardOnIce) November 27, 2018

The most frustrating error for me in Python/ Spyder is «unindent does not match any outer indentation level». tab, space still not working….. I hate the error with passion #python #100DaysOfMLCode #ai #MachineLearning

— Oladeji Stephen (@RealSaintSteven) October 9, 2018

Understanding Python Indentation

The ICMEStudio YouTube channel shot a popular video clarifying how indentation works in Python:

How To Prevent The Indentation Error From Occuring?

The guidelines below are just the basic steps to follow in preventing indentation error occurs.

  • First, it is important to align the codes with an opening delimiter. By using Python’s implicit line linking inside brackets, braces, and parentheses, these continuation lines should align wrapped elements vertically. A hanging indent can be used as well.

Note: In using a hanging indent, no arguments must be placed on the very first line. Also, to clearly differentiate the continuation line, an additional indentation must be used.

  • Add four spaces to determine arguments from the rest. This will be considered as an extra level of indentation.
  • Add an additional indentation level for hanging indents.

Note: Remember that the 4-space rule is nonmandatory for hanging indents.

How To Fix It?

The number of indentation always matters. Having a missing or extra space could cause an unexpected behavior that we consider the error. Within the similar block of code, statements should be intended at the same indentation level. So, here are preferred methods to fix the error.

Fix 1

For those who use Sublime Text as their source code editor, follow these steps:

  1. Set Sublime Text to use tabs for indentation.
  • Go to view
  • Choose indentation
  • Convert Indentation to Tabs.
  1. Go to the sub-menu and look for the ‘Indent Using Spaces’ option and uncheck it.

This will automatically resolve the issue.

Note: Injecting copy-pasted code could be a source of the problem. So, avoid doing it. Space and tab problems can be prevented if you will display invisible characters within your text editor. It will quickly resolve indentation-related errors.

Also, you can avoid the issue by using the package Anaconda. Try following these steps:

  1. Install Anaconda.
  2. Open your sublime file.
  3. Look for ‘Open Spaces’ and right click.
  4. Choose Anaconda.
  5. Click on auto format.
  6. Click Done or Press CTRL+ALT+R

Video Guide: Sublime Text Line and Indentation Tools

Fix 2

For Python’s IDLE editor users, follow the steps below, if it suggests one similar message:

1) Choose All, e.g. Ctrl + A

2) Select Format -> Untabify Region

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

This works well for Python 2.5.4 and Python 3.4.2

Note: Make sure not to mix space with the tab because Python is whitespace sensitive.

Fix 3

For Vim users, follow these steps and it will indent everything. It will also clear up any space you threw in.

  1. Hit escape.
  2. Type gg=G

Fix 4

For ATOM users, you can do these steps to resolve the error:

  1. Go to Packages.
  2. Choose Whitespace.
  3. Convert Spaces to Tabs.
  4. Check your file indentation:

python -m tabnanny yourFile.py

or

>python

>>> help(“yourFile.py”)

And here’s another way to resolve the issue. This method also works for ATOM users.

  1. Go to Packages.
  2. Choose Whitespace.
  3. Remove trailing whitespaces.

Fix 5

For indentation-related issues in Notepad++, you can fix the problem by doing this:

  • For unexpected indentation:
  1. Go to the Search tab.
  2. Tap on replacing.
  3. Hit the radio button EXTENDED below.
  4. Replace t with four spaces.
  • For Outer indentation Level:
  1. Go to.
  2. Search tab.
  3. Tap on replacing.
  4. Hit the radio button EXTENDED below.
  5. Replace n with nothing.

Video Guide: How To Indent HTML Tags In Notepad++

Fix 5

For Spyder users, look carefully at your ‘if statement’ and make sure that all if, elif and else statements have exactly the same spacing as if they are in the same line.

Use the reference below:

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

Forum Feedback

To understand more about IndentationError: unindent does not match any outer indentation level, we search through several Python message boards and support forums.

python IndentationError unindent does not match any outer indentation level

In general, users wanted information about IndentationError: unindent does not match any outer indentation level Vim/ ATOM/Jupyter/Notepad C++. They also wanted to know about how to handle IndentationError: unindent does not match any outer indentation level in Django and Pycharm.

A Python novice shared that he completed his code, and he was certain that he has programmed it correctly.

  • However, he was getting an error that he didn’t know the meaning of.
  • It said, “IndentationError: unindent does not match any outer indentation level.”
  • So, he reached to the programming community for advice.
  • They said that the most probable cause for such an error would be that he had mixed tabs with spaces which resulted in the wrong indentation.
  • What they recommend was to search for tabs and then replaces the tabs with spaces.

Another user also ran into the same error. Following advice from other Python programmers, he looked at what tabs and spaces he had used. He discovered that his first line was spaced, but he had used tabs for the rest of the code. He was surprised by that because he didn’t know that tabs and spaces mattered in Python.

An individual remarked that it could be tricky to remember how to use tabs and space properly in Python. That’s why he recommended that you use the right text redactor to edit your Python code and mentioned that you could configure it to replace tabs with spaces so that you could avoid IndentationError: unindent does not match any outer indentation level errors.

python 3.4 3 unindent does not match any outer indentation level error http://t.co/vkXNJs9fb8 http://t.co/SgsIGGpwz7 #Python via @dv_geek

— Python Questions (@Python_Quest) June 25, 2015

Another poster also mentioned that spaces are preferred in Python and that you can employ SublimeText because it shows spaces as dots. In this way, you can quickly find out where you’ve used tabs and fix it on the spot.

A poster explains that if you have used a tab somewhere instead of a space, you can change it quickly in Sublime. Simply go to View –> Indentation –> Convert Indentation to Tabs. He also recommends that you uncheck “Indent Using Spaces” in the same menu so that you don’t make an accidental mistake.

A Python user says that if you’re using ATOM, you also have the option to convert tabs to spaces when you get the indentation error. He explains that you must click on Packages > Whitespace > Convert Spaces to Tabs, and you’re ready to go.

Another forum member comments when you get IndentationError: unindent does not match any outer indentation level errors you can check for problems using “python -m tabnanny yourfile.py”. However, several users who have tried that solution said that they didn’t get any output and one poster complained that it showed an error in the wrong line.

my first python error…. IndentationError: unindent does not match any outer indentation level

— Hruhiko Soma (@harupiko) September 6, 2007

A Python expert explains that it’s true that spaces are preferred according to the Python style guide. However, as long as you use only spaces or only tabs you shouldn’t get indentation errors, but using both will cause a conflict.

Another user explains that besides mixing tabs and spaces in code, other sources of indentation problem will arise if you copy and paste code lines. He also suggests that you always display invisible characters like spaces/tabs in your editor so that you can spot a mismatch.

A forum commentator shares that his problem with IndentationError: unindent does not match any outer indentation level came from an incorrect configuration of PyDeck. That’s why he advises that you check the settings to make sure that they are the correct one. He observes that Python is very strict with how you should structure your code and that you should read the style guide again if you’re not sure which rules apply to Python.

Another poster states that you should rely on a good Python IDE if you’re serious about programming. He points about that an IDE can identify and highlight wrong indentations so that you don’t have to wonder what’s wrong with the code.

A beginner programmer said that he followed the advice of fellow Python users and that he replaced tabs with spaces. However, he still kept getting the same indentation error. It turned out that his indentation wasn’t consistent. He didn’t know that he should stick to four spaces per level of indentation, which is the recommended number.

Summing Up

Coding is a crucial and sensitive task. This is why programmers need to be extra careful in inserting program languages. In resolving issues like the indentation error, different approaches could be used to resolve the problem.

Also, there are things you need to know ahead. First, check the source code editor you are using because different procedure applies. Follow the correct settings and know the possible causes that may trigger the system to behave differently.

Also, you can rely on forums online and video tutorials since people around the world encounter the same issues as yours and might be able to share how they resolve it their way. Be knowledgeable and resourceful enough to gather more information as solutions may vary because of the system compatibility.

And lastly, don’t hesitate to share what works for you because it could also save someone on the other side.

Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.

Понравилась статья? Поделить с друзьями:
  • Unimac сушильная машина ошибка af
  • Unic ошибка е11
  • Unhandled error during execution of setup function
  • Unhandled error during execution of scheduler flush this is likely a vue internals bug
  • Unhandled error during execution of render function