简体   繁体   English

期望一个缩进的块python

[英]expected an indented block 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

I'm learning Python though main doc. 我正在通过主要文档学习Python。 This chapter (4.2. for Statements) .But when i'm practicing it on UBUNTU TERMINAL it gave me above error ? 本章 (4.2。对于陈述)。但是当我在UBUNTU TERMINAL上练习时,它给了我上面的错误? what's that mean ? 那是什么意思 ?

As it says, your print statement needs to be indented since it is in a for loop 正如它所说,你的print语句需要缩进,因为它在for循环中

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

In python, indentations are not simply for readability, they are a requirement. 在python中,缩进不仅仅是为了可读性,它们是一个要求。 The following two are NOT the same thing 以下两个不是一回事

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

AND

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

Indentation is basically placing whitespaces before certain lines in your code with tab or space 缩进基本上是在代码中的某些行之前使用制表符空格放置空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM