Python中 block 前的冒号有什么作用?
例子:
if n == 0:
print "The end"
最佳答案
冒号用于声明缩进 block 的开始。
从技术上讲,没有必要; block 完成后,您可以缩进和取消缩进。但是,基于 Python koan “显式优于隐式”(EIBTI),我相信 Guido 故意使冒号成为强制性的,因此 任何 声明 应该 后跟缩进代码以冒号结尾。 (如果您在冒号后继续,它也允许单行,但这种样式并未广泛使用。)
它还使语法感知自动缩进编辑器的工作更容易,这也计入了决定。
这个问题原来是 Python FAQ ,我找到了 Guido here 的答案之一:
Why are colons required for the if/while/def/class statements?
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
if a == b print a
versus
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 - Python中 block 之前的冒号的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/215581/