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 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 :
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
compound_stmt ::= [ if_stmt]
| [ for\_stmt]
| [ try\_stmt]
| [ with\_stmt]
| [ classdef]
suite ::= [ stmt_list] NEWLINE | NEWLINE INDENT [statement]+ DEDENT
statement ::= [ stmt_list] NEWLINE | [compound_stmt]
stmt_list ::= [ simple_stmt] (“;” [simple_stmt])* [“;”]
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).