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

这是因为制表符和空格混淆了。 您可以删除所有空格并用制表符替换它们。

或者, 试着这样写:

#!/usr/bin/python -tt

在代码的开头。这一行解决了制表符和空格之间的任何差异。

每当我遇到这个错误时,都是因为我在编辑器中混淆了制表符和空格。

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

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

    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 

如果你使用notepad++,用扩展搜索模式做一个“替换”来找到\t并替换为四个空格。