当我编译下面的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?
当我编译下面的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
在任何情况下,确保清楚地说明为什么它是一个空函数——对于你自己,或者对于将使用你的代码的同事
其他回答
使用Visual studio代码
如果你使用vs code than,它将使用下面的简单步骤将所有混合缩进转换为空格或制表符。
按Ctrl + Shift + p 使用空格输入缩进 按回车键
我使用Jupyter笔记本电脑,尝试了上面几乎所有的解决方案(适应我的场景),但都没有用。然后我逐行删除每行的所有空格并用制表符替换。这就解决了问题。
您确定在缩进空白中没有混合制表符和空格吗?(这会导致错误。)
注意,建议不要在Python代码中使用制表符。请参阅样式指南。您应该配置notepad++为制表符插入空格。
只是一个补充。我在notepad++中有一个类似的缩进问题。
Unexcepted缩进 外压痕水平 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在用四个空格替换\t 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在替换\n与无
如果你使用Python的IDLE编辑器,你可以按照它在类似错误消息中建议的那样做:
1)全选,如Ctrl + A
2)进入Format -> Untabify Region
3)再次检查缩进是否正确,保存并重新运行程序。
我使用的是Python 2.5.4