期望一个缩进的块python

时间:2014-04-06 05:19:31

标签: 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。This chapter(4.2。用于语句)。但是当我在UBUNTU TERMINAL上练习它时,它给了我上面的错误?这是什么意思?

1 个答案:

答案 0 :(得分:2)

正如它所说,你的print语句需要缩进,因为它在for循环中

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print w, len(w)
cat 3
window 6
defenestrate 12

在python中,缩进不仅仅是为了可读性,它们是一个要求。以下两个是 NOT 相同的东西

if 1==1:
print 'yes'   #incorrect indentation, not accepted by python

if 1==1:
    print 'yes'   #correct indentation, accepted by python

缩进基本上是在代码中的某些行之前使用 tab space

放置空格