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


当前回答

因为我意识到没有特定于spyder的答案,我将添加一个: 基本上,仔细查看你的if语句,并确保所有if, elif和else都有相同的间距,即它们在开始时处于同一行,如下所述:

def your_choice(answer):
    if answer>5:
        print("You're overaged")
    elif answer<=5 and answer>1: 
            print("Welcome to the toddler's club!")
    else:
            print("No worries mate!")

其他回答

我昨天也有同样的问题,这是缩进错误,正在使用崇高的文本编辑器。我花了几个小时来修复它,最后我把代码复制到VI文本编辑器中,它工作得很好。Ps python对空格太敏感,请确保不要混合空格和制表符。

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

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

    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与无

对于Spyder用户goto 修复缩进 立即解决这个问题

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