预期缩进块 Python
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
File "<stdin>", line 2
print w, len(w)
^
IndentationError: expected an indented block
>>> print w, len(w)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'w' is not defined
>>> for w in words:
... print w, len(w)
File "<stdin>", line 2
print w, len(w)
^
IndentationError: expected an indented block
我正在通过主文档学习Python。这一章(4.2. for语句)讲得不错。但是当我在UBUNTU终端上练习的时候,出现了上面的错误?这是什么意思呢?
1 个回答
2
正如所说,你的 print
语句需要缩进,因为它在一个 for
循环里面。
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
cat 3
window 6
defenestrate 12
在Python中,缩进不仅仅是为了让代码看起来更整齐,它是必须的。下面这两种写法是完全不同的。
if 1==1:
print 'yes' #incorrect indentation, not accepted by python
而且
if 1==1:
print 'yes' #correct indentation, accepted by python
缩进就是在代码的某些行前面加上空格,可以用 tab 键或者 space 键来实现。