views:

15568

answers:

6

When I compile the code below, I get

IndentationError: unindent does not match any outer indentation level
 
import sys

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

Any ideas why?

+5  A: 

EDIT: 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)
Kevin Tighe
yeah, I had to really space over the inner loop part at the last two lines (in SO only). Not sure why...
cbrulak
my first line, "result = 0" (which should ahve been 1, thanks for correcting) was spaced while the rest was tabbed, darn, didn't know python was like that
cbrulak
Yeah, that can be tricky. I use emacs to edit python, and I have it setup to always replace tabs with spaces in py files so I don't have this problem. Notepad++ might have an option like this as well.
Kevin Tighe
+1  A: 

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
I had to change the editing in SO, strange. See my updated "Edit" note in the question
cbrulak
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
+4  A: 

Are you sure you are not mixes 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.

zdan
+1  A: 

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

Dana
+3  A: 

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é