我为什么会收到“IndentationError: expected an indented block”?
考虑一下:
if len(trashed_files) == 0 :
print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "*" :
for tfile in trashed_files :
try:
tfile.restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
elif index == "" :
print "Exiting"
else :
index = int(index)
try:
trashed_files[index].restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
我得到了:
elif index == "" :
^
IndentationError: expected an indented block
6 个回答
我之前也遇到过这个问题,后来通过一个类似问题的回答发现,问题出在我没有正确缩进文档字符串。可惜的是,IDLE(一个编程环境)在这方面没有给出有用的反馈,但当我修正了文档字符串的缩进后,问题就解决了。
具体来说——下面是会导致缩进错误的坏代码:
def my_function(args):
"Here is my docstring"
....
下面是避免缩进错误的好代码:
def my_function(args):
"Here is my docstring"
....
注意:我并不是说这就是问题所在,而是说这可能是,因为在我的情况下,确实是这样!
其实在Python中,缩进有很多需要注意的地方:
Python对缩进非常讲究。
在很多其他编程语言中,缩进不是必须的,但可以让代码更容易阅读。而在Python中,缩进代替了关键字 begin / end
或 { }
,所以是必须的。
这会在代码执行之前检查,因此即使有缩进错误的代码从未被执行,它也不会工作。
缩进错误有不同类型,了解它们会很有帮助:
1. "IndentationError: expected an indented block"
出现这种错误主要有两个原因:
- 你有一个":",但后面没有缩进的代码块。
这里有两个例子:
例子1,没有缩进的代码块:
输入:
if 3 != 4:
print("usual")
else:
输出:
File "<stdin>", line 4
^
IndentationError: expected an indented block
输出提示你在第4行的 else:
语句后面需要有一个缩进的代码块。
例子2,缩进不正确的代码块:
输入:
if 3 != 4:
print("usual")
输出:
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
输出提示你在第2行的 if 3 != 4:
语句后面需要有一个缩进的代码块。
- 你在使用Python2.x,并且混用了制表符和空格:
输入:
def foo():
if 1:
print 1
请注意,在if前面是一个制表符,而在print前面有8个空格。
输出:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
这里的情况比较复杂,看起来有一个缩进的代码块……但正如我所说,我混用了制表符和空格,这样是不对的。
- 你可以在 这里 获取一些信息。
- 把所有的制表符去掉,换成四个空格。
- 并且设置你的编辑器自动这样做。
2. "IndentationError: unexpected indent"
缩进代码块是很重要的,但只对需要缩进的代码块进行缩进。所以这个错误的意思是:
- 你有一个缩进的代码块,但前面没有":"。
例子:
输入:
a = 3
a += 3
输出:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
输出提示在第2行不应该有缩进,所以你需要把它去掉。
3. "TabError: inconsistent use of tabs and spaces in indentation"(仅限python3.x)
- 你可以在 这里 获取一些信息。
- 基本上就是,你在代码中混用了制表符和空格。
- 这是不好的做法。
- 把所有的制表符去掉,换成四个空格。
- 并且设置你的编辑器自动这样做。
最后,回到你的问题:
只需查看错误提示的行号,然后根据之前的信息进行修复。
根据错误信息,你的代码有缩进错误。这可能是因为你在代码中同时使用了制表符(Tab)和空格。