Advertisement
Advertisement


IndentationError: unindent does not match any outer indentation level


Question

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?

2019/01/14
1
604
1/14/2019 7:13:36 PM

Accepted Answer

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)
2017/01/27
702
1/27/2017 3:05:40 PM

IMPORTANT: Spaces are the preferred method - see PEP008 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.

2016/01/09

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

2009/02/04

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.

2011/08/25

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

2009/01/29

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

2019/08/15

Source: https://stackoverflow.com/questions/492387
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]