如何在Python中创建缩进块?

-1 投票
2 回答
4932 浏览
提问于 2025-04-16 04:03

比如,我应该怎么在Python中输入这个代码,以确保它的缩进是正确的呢?

if 1 + 2 == 2:
   print "true"
   print "this is my second line of the block"
   print "this is the third line of the block"

2 个回答

2

在Python中,“正确”的缩进意味着要“保持一致”。

“请注意,基本代码块中的每一行都必须缩进相同的距离。” 参考链接

http://docs.python.org/tutorial/controlflow.html#intermezzo-coding-style 总结了你需要遵循的其他规则,以便按照 PEP-8 编写“正确”的Python代码。

4

这是正确缩进的示例。

if 1 + 2 == 2:
    print "true"
    print "this is my second line of the block"
    print "this is the third line of the block"

如果你在使用Python的交互式环境(REPL)... 只需在第一行前不加空格,然后在代码块内的缩进行使用任意但一致数量的空格(标准是用空格)。

编辑: 根据要求添加 --

由于你有Java的背景,可以大致把Python的缩进规则看作是Java使用的花括号。比如,可以这样添加一个else语句:

if thisRef is True:
    print 'I read the python tutorial'
else
    print 'I may have skimmed a blog about python'

如果你愿意,还可以模仿一种被Python爱好者称为"bracist"的语言,使用注释来帮助你理解 --

if thisRef is True: # {
    print 'I read the python tutorial'
# }
else # {
    print 'I may have skimmed a blog about python'
# }

简单来说,通过改变缩进的层级,你就改变了代码块的深度。

我无法强调阅读像PEP8这样的文档的重要性,这在第4.8节中有提到,或者其他关于Python缩进基本规则的文档。

撰写回答