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


当前回答

在原子

Packages > Whitespace > Convert Spaces to Tabs

然后再次检查文件缩进:

python -m tabnanny yourFile.py

or

>python
>>> help("yourFile.py")

其他回答

我在Ubuntu操作系统中使用Sublime文本。要修复此问题,请转到

>缩进->将缩进转换为制表符

我犯了同样的错误,因为另一件事,不是关于制表符和空格。我有第一个比其他的稍微多一点缩进:更深入。如果它只是一两个空间,你可能会在一个很长的代码块之后检查它。文档字符串也是一样:

"""comment comment 
comment
"""

它们还需要对齐,请参阅同一页上的另一个答案。

可复制的几行:

if a==1:
    print('test')
 else:
    print('test2')

抛出:

  File "<ipython-input-127-52bbac35ad7d>", line 3
    else:
         ^
IndentationError: unindent does not match any outer indentation level

看起来是压痕问题。你不必在Python中匹配花括号,但你必须匹配缩进级别。

防止空格/制表符问题的最好方法是在文本编辑器中显示不可见的字符。这将为您提供一种快速防止和/或解决缩进相关错误的方法。

此外,注入复制粘贴的代码是这类问题的常见来源。

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

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

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

这一行:result = result * i应该缩进(它是for循环的主体)。

或者-你混合了空格和制表符