当我编译下面的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?


当前回答

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

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

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

其他回答

只是一个补充。我在notepad++中有一个类似的缩进问题。

Unexcepted缩进 外压痕水平 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在用四个空格替换\t 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在替换\n与无

首先,只是提醒你有一个逻辑错误,你最好保持result=1,否则即使在循环运行后,你的输出也将是result=0。

其次,你可以这样写:

import sys

def Factorial(n): # Return factorial
  result = 0
  for i in range (1,n):
     result = result * i

  print "factorial is ",result
  return result

留下一行将告诉python shell FOR语句已经结束。如果你有使用python shell的经验,那么你就能理解为什么我们必须留下一行。

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

IndentationError:期望一个缩进的块

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

class Person:
    # pass

x = 10
def test():
    # pass

x = 10

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

class Person:
    # pass

# x = 10
def test():
    # pass

# x = 10

我得到的错误如下:

SyntaxError:解析时意外的EOF

重要的是: 空格是首选方法-请参阅PEP 8缩进和制表符或空格?(感谢@Siha。)

Sublime Text用户:

设置Sublime Text使用制表符缩进: 将缩进转换为制表符

在上面的同一子菜单中取消使用空格缩进选项。 这将立即解决这个问题。

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

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

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