为什么在这个python片段中允许分号?

2024-04-24 01:18:39 发布

您现在位置:Python中文网/ 问答频道 /正文

Python不保证在结束语句时使用分号。 为什么允许这样做?

import pdb; pdb.set_trace()

Tags: importtrace语句pdbset
3条回答

Python使用;作为分隔符,而不是结束符。您还可以在一行的末尾使用它们,这使它们看起来像语句结束符,但这是合法的,因为在Python中,空白语句是合法的——在结尾包含分号的一行是两个语句,第二个是空白的。

http://docs.python.org/reference/compound_stmts.html

Compound statements consist of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print statements are executed:

if x < y < z: print x; print y; print z 

总结:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | decorated
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

Python不需要分号来终止语句。如果您希望将多个语句放在同一行上,可以使用分号分隔语句。

现在,为什么允许这样做?这是一个简单的设计决定。我不认为Python需要这个分号,但是有人认为将它添加到语言中会更好。

相关问题 更多 >