python - Python中 block 之前的冒号的目的是什么?

标签 python syntax

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/

相关文章:

python - 使用 skorch 和 sklearn 管道的多输出回归由于 dtype 导致运行时错误

Windows 上的 python setup.py 安装语法错误

objective-c - 想学Objective-C 但是语法很乱

ruby - `:key => "值"` and `键: "value"` hash notations?有区别吗

python - 是否可以在 RabbitMQ 队列之间移动/合并消息?

python - 使用 mysql 创建的表,但我无法使用 python 从它中进行选择

python - 使用张量数组时 SymPy 中的类型错误

python - Pyspark 数据框连接有少量重复的列名和少量没有重复的列

php - 如何将 2 个数组分组

python - 是否可以转义 Python 中的保留字?