缩进错误:未对齐缩进与任何外部缩进级别匹配,尽管缩进看起来正确。

793
当我编译下面的Python代码时,我得到以下错误:

IndentationError: unindent does not match any outer indentation level


import sys

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

为什么?

12
我遇到了同样的错误,但是我碰巧将一个方法在代码中向左缩进了一些,这导致在它下面的下一个方法中出现了这个错误。因此,这个错误不仅可能是由于混合使用制表符和空格造成的。 - Prof. Falken
27
我正在使用Sublime Text 3。我有一个Django项目。我使用“View > Indentation > Intent Using Spaces”修复了错误。 - abhimanyuaryan
3
我发现使用IDLE可以更轻松地找到缩进问题。它能清晰地找出大多数编辑器无法发现的缩进错误。 - Dennis Gathagu
2
Sublime 3.2.2:查看 > 缩进 > 将缩进转换为空格 -- 对我有用 - Impermanence
2
您可以通过查看 Markdown 源代码 看到问题所在: 最后三行前面有制表符。但 Stack Overflow 在呈现时会将制表符转换为 4 个空格,因此该问题就消失了。 - wjandrea
显示剩余2条评论
32个回答

0
我遇到了类似下面的错误:

IndentationError: expected an indented block

当我忘记在下面的类或函数中添加 pass,然后在类或函数后面编写其他代码时,就会出现上述错误。
class Person:
    # pass

x = 10

def test():
    # pass

x = 10

当类或函数后面没有编写其他代码时,如下所示:

class Person:
    # pass

# x = 10

def test():
    # pass

# x = 10

我遇到了以下错误:

SyntaxError: 解析时意外的EOF


0

我在pylint中遇到了这个问题,是由于括号放错位置导致的。

我添加这个答案是因为我花了很多时间寻找制表符。但在这种情况下,与制表符或空格无关。

    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 

将制表符转换为空格。https://dev59.com/InRB5IYBdhLWcg3w9L3n - Wolfpack'08

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接