当我编译下面的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?
当前回答
重要的是: 空格是首选方法-请参阅PEP 8缩进和制表符或空格?(感谢@Siha。)
Sublime Text用户:
设置Sublime Text使用制表符缩进: 将缩进转换为制表符
在上面的同一子菜单中取消使用空格缩进选项。 这将立即解决这个问题。
其他回答
我定义了一个函数,但它除了函数注释之外没有任何内容……
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
在任何情况下,确保清楚地说明为什么它是一个空函数——对于你自己,或者对于将使用你的代码的同事
只是一个补充。我在notepad++中有一个类似的缩进问题。
Unexcepted缩进 外压痕水平 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在用四个空格替换\t 去---->搜索选项卡---->点击替换---->点击单选按钮扩展下面->现在替换\n与无
在原子
去
Packages > Whitespace > Convert Spaces to Tabs
然后再次检查文件缩进:
python -m tabnanny yourFile.py
or
>python
>>> help("yourFile.py")
对于Spyder用户goto 修复缩进 立即解决这个问题
另一种纠正缩进错误的方法是复制您的 代码到PyCharm(如果您已经配置了),并重新格式化文件 它将自动正确地缩进。