当我编译下面的Python代码时,我得到

IndentationError: unindent不匹配任何外部缩进级别


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?


当前回答

这可能是因为上面的函数没有以同样的方式缩进。 即。

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")

其他回答

我得到了类似的错误如下:

IndentationError:期望一个缩进的块

当我忘记把pass传给下面的类或函数时,然后在类或函数之后编写其他代码,如下所示:

class Person:
    # pass

x = 10
def test():
    # pass

x = 10

并且,当其他代码没有在类或函数之后编写时,如下所示:

class Person:
    # pass

# x = 10
def test():
    # pass

# x = 10

我得到的错误如下:

SyntaxError:解析时意外的EOF

对于Atom用户,Packages ->whitspace ->删除尾随空格 这对我很有效

我得到这个错误,即使我没有任何制表符在我的代码,原因是有一个多余的右括号在我的代码的某处。我应该早点算出来的,因为它把等号前后的空格弄乱了……如果在IDE中运行Reformat code(或手动运行autopep8)后仍然发现任何错误,请确保所有括号都匹配,从第一个等号前后的奇怪空格开始。

我定义了一个函数,但它除了函数注释之外没有任何内容……

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

它喊道:

  File "foobar.py", line 69

                                ^
IndentationError: expected an indented block

(注意^标记所指向的行是空的)

--

多个解决方案:

1:只注释掉函数

2:添加函数注释

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

3:添加不做任何事情的行

def foo(bar):
    0

在任何情况下,确保清楚地说明为什么它是一个空函数——对于你自己,或者对于将使用你的代码的同事

对于Spyder用户goto 修复缩进 立即解决这个问题