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


当前回答

我正在使用Sublime Text 3与Flask项目。我修复了使用视图>缩进>选项卡宽度:4后未选择缩进使用空间的错误

其他回答

我犯了同样的错误,因为另一件事,不是关于制表符和空格。我有第一个比其他的稍微多一点缩进:更深入。如果它只是一两个空间,你可能会在一个很长的代码块之后检查它。文档字符串也是一样:

"""comment comment 
comment
"""

它们还需要对齐,请参阅同一页上的另一个答案。

可复制的几行:

if a==1:
    print('test')
 else:
    print('test2')

抛出:

  File "<ipython-input-127-52bbac35ad7d>", line 3
    else:
         ^
IndentationError: unindent does not match any outer indentation level

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

gg=G

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

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

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

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

    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 

我得到了类似的错误如下:

IndentationError:期望一个缩进的块

当我忘记把pass传给下面的类或函数时,然后在类或函数之后编写其他代码,如下所示:

class Person:
    # pass

x = 10
def test():
    # pass

x = 10

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

class Person:
    # pass

# x = 10
def test():
    # pass

# x = 10

我得到的错误如下:

SyntaxError:解析时意外的EOF