Syntax: Statements
Simple Statements #
Simple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:
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 and with specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions (def and class) are also syntactically compound statements.
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. The suite is usually written as one or more indented statements on subsequent lines.
keyword expression :
statement
statement …
A suite can also be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon.
keyword expression : statement ; statement
The latter form cannot 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
Summarizing:
compound_stmt ::= [ if_stmt][1]
| [while\_stmt][2]
| [ for\_stmt][3]
| [ try\_stmt][4]
| [ with\_stmt][5]
| [funcdef][6]
| [ classdef][7]
suite ::= [ stmt_list][8] NEWLINE | NEWLINE INDENT [statement][9]+ DEDENT
statement ::= [ stmt_list][8] NEWLINE | [compound_stmt][10]
stmt_list ::= [ simple_stmt][11] (“;” [simple_stmt][11])* [“;”]
Note that statements always end in a NEWLINE possibly followed by a
DEDENT token. 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).
