Python中块前冒号的目的是什么? [英] What is the purpose of the colon before a block in Python?
问题描述
Python 中块前冒号的作用是什么?
What is the purpose of the colon before a block in Python?
示例:
if n == 0:
print "The end"
推荐答案
冒号用于声明缩进块的开始.
The colon is there to declare the start of an indented block.
从技术上讲,没有必要;您可以在块完成后缩进和取消缩进.然而,基于 Python koan 显式优于隐式"(EIBTI),我相信 Guido 故意使冒号成为强制性的,所以 任何 声明 应该 后跟缩进代码都以冒号结尾.(如果您在冒号之后继续,它也允许单行,但这种样式并未广泛使用.)
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the Python koan "explicit is better than implicit" (EIBTI), I believe that Guido deliberately made the colon obligatory, so any statement that should be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
它还使语法感知自动缩进编辑器的工作更容易,这也计入决策.
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
这个问题原来是一个Python 常见问题解答,我找到了 Guido here:
This question turns out to be a Python FAQ, and I found one of its answers by Guido here:
为什么 if/while/def/class 语句需要冒号?
需要冒号主要是为了提高可读性(实验性 ABC 语言的结果之一).考虑一下:
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
if a == b
print a
对比
if a == b:
print a
请注意第二个更容易阅读.进一步注意冒号如何引出此常见问题解答中的示例;这是英语的标准用法.
Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
另一个次要原因是冒号使具有语法突出显示的编辑器更容易;他们可以查找冒号来决定何时需要增加缩进,而不必对程序文本进行更精细的解析.
Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
这篇关于Python中块前冒号的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!