7. 复合语句 Compound statements

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.

复合语句由其它语句(组)构成; 它某种方式影响或控制其它语句的执行.一般地, 复合语句跨越多个行, 但是一个完整的复合语句也可以简化在一行中.

The if, while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.

if ,while和for语句实现的传统的控制流机制. try语句为一组语句指定异常处理器和/或清除代码.函数定义和类定义在句法上也被看作复合语句.

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:

复合语句由一个或多个"子句"组成.一个子句由一个头和一个"代码序列"组成.一个具体的复合语句的所有子句具有相同的缩进层次.每个子句头以一个唯一的标识关键字开始, 并以一个冒号结果.一个语句序列, 是由该子句所控制的一组语句, 一个语句序列可以包括一个或多个分号 -- 与子句头同行的一串简单语句;或者它可以是以随后的各行中缩进的语句. 仅在后者的情况下子句序列允许包括有嵌套的复合语句, 下面这样是非法的, 这样处理大部分原因是如果其后面有else子句的话, 语义就不太清晰了.

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:

也要注意在这样的上下文中, 分号的优先级比冒号的高, 所以在下面的例子中, 要么执行全部的print语句, 要么一个也不执行:

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

Summarizing:

总结:

compound_stmt  ::=  if_stmt
    | while_stmt
    | for_stmt
    | try_stmt
    | funcdef
    | classdef
suite  ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement  ::=  stmt_list NEWLINE | compound_stmt
stmt_list  ::=  simple_stmt (";" simple_stmt)* [";"]
Download entire grammar as text.

Note that statements always end in a NEWLINEpossibly followed by a DEDENT.Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the `dangling else' problem is solved in Python by requiring nested if statements to be indented).

注意以NEWLINE结尾的语句可能后缀一个DEDENT. 同时注意到可选的续行子句通常以不能开始一个语句的某个关键字开始, 因此这里没有歧义("不定的else"问题已经由Python对嵌套的语句要求缩进而解决掉了).

The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.

为了叙述清楚, 以下章节中的每个子句的语法规则格式都被分行说明.



子节目录