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


当前回答

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

Sublime Text用户:

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

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

其他回答

为了它的价值,我的文档字符串缩进太多,这也抛出相同的错误

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

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

如果你使用Python的IDLE编辑器,你可以按照它在类似错误消息中建议的那样做:

1)全选,如Ctrl + A

2)进入Format -> Untabify Region

3)再次检查缩进是否正确,保存并重新运行程序。

我使用的是Python 2.5.4

实际上,我从一个错误的地方得到了这个。

我加上这个答案是因为我花了很多时间寻找标签。 在本例中,它与制表符或空格无关。

    def some_instance_function(self):

        json_response = self.some_other_function()

        def compare_result(json_str, variable):
            """
            Sub function for comparison
            """
            json_value = self.json_response.get(json_str, f"{json_str} not found")

            if str(json_value) != str(variable):
                logging.error("Error message: %s, %s", 
                    json_value,
                    variable) # <-- Putting the bracket here causes the error below
                    #) <-- Moving the bracket here fixes the issue
                return False
            return True

        logging.debug("Response: %s", self.json_response)
        #        ^----The pylint error reports here 

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

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

我昨天也有同样的问题,这是缩进错误,正在使用崇高的文本编辑器。我花了几个小时来修复它,最后我把代码复制到VI文本编辑器中,它工作得很好。Ps python对空格太敏感,请确保不要混合空格和制表符。