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


当前回答

例如:

1. def convert_distance(miles):
2.   km = miles * 1.6
3.   return km

在这段代码中,我遇到了同样的情况。只需要删除之前的缩进空格 第2行和第3行,然后使用制表符或空格。不要两者都用。在python中编写代码时,给予适当的缩进。 对于Spyder去源代码>修复缩进。同样适用于VC代码和sublime文本或任何其他编辑器。固定缩进。

其他回答

我在Ubuntu操作系统中使用Sublime文本。要修复此问题,请转到

>缩进->将缩进转换为制表符

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

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

为了它的价值,我的文档字符串缩进太多,这也抛出相同的错误

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

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

print Factorial(10)

我定义了一个函数,但它除了函数注释之外没有任何内容……

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

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