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

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

其他回答

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

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

或者, 试着这样写:

#!/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 

我使用Jupyter笔记本电脑,尝试了上面几乎所有的解决方案(适应我的场景),但都没有用。然后我逐行删除每行的所有空格并用制表符替换。这就解决了问题。

我得到这个错误,即使我没有任何制表符在我的代码,原因是有一个多余的右括号在我的代码的某处。我应该早点算出来的,因为它把等号前后的空格弄乱了……如果在IDE中运行Reformat code(或手动运行autopep8)后仍然发现任何错误,请确保所有括号都匹配,从第一个等号前后的奇怪空格开始。