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

其他回答

另一种纠正缩进错误的方法是复制您的 代码到PyCharm(如果您已经配置了),并重新格式化文件 它将自动正确地缩进。

其他的海报可能是正确的…可能会在制表符中混入空格。尝试用一些空格替换所有的制表符。

试试这个:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

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

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

    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++中有一个类似的缩进问题。

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

您确定在缩进空白中没有混合制表符和空格吗?(这会导致错误。)

注意,建议不要在Python代码中使用制表符。请参阅样式指南。您应该配置notepad++为制表符插入空格。