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


当前回答

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

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

其他回答

如果你正在使用Vim,点击escape,然后输入

gg=G

这将自动缩进所有内容,并将清除您所扔进去的任何空间。

为了方便地检查制表符/空格的问题,你可以这样做:

python -m tabnanny yourfile.py

当然,你也可以设置正确的编辑器:-)

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

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

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

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

    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 

这可能是因为上面的函数没有以同样的方式缩进。 即。

class a:
    def blah:
      print("Hello world")
    def blah1:
      print("Hello world")