Skip to main content

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, while the with statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements. A compound statement consists 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 if Statement

The if statement is used for conditional execution:
It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true; then that suite is executed. If all expressions are false, the suite of the else clause, if present, is executed:

The while Statement

The while statement is used for repeated execution as long as an expression is true:
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

The for Statement

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:
The expression list is evaluated once; it should yield an iterable object. An iterator is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments, and the suite is executed:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item.

The try Statement

The try statement specifies exception handlers and/or cleanup code for a group of statements:

except Clause

The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started:
For an except clause with an expression, the expression must evaluate to an exception type or a tuple of exception types. Parentheses can be dropped if multiple exception types are provided and the as clause is not used:

except* Clause

The except* clause(s) specify one or more handlers for groups of exceptions (BaseExceptionGroup instances):
A try statement can have either except or except* clauses, but not both.

finally Clause

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause:

The with Statement

The with statement is used to wrap the execution of a block with methods defined by a context manager:
The execution of the with statement proceeds as follows:
  1. The context expression is evaluated to obtain a context manager
  2. The context manager’s __enter__() method is invoked
  3. If a target was included, the return value from __enter__() is assigned to it
  4. The suite is executed
  5. The context manager’s __exit__() method is invoked

The match Statement

The match statement is used for pattern matching:
Pattern matching takes a pattern as input (following case) and a subject value (following match). The pattern is matched against the subject value:

Patterns

Literal Patterns

A literal pattern corresponds to most literals in Python:

Capture Patterns

A capture pattern binds the subject value to a name:

Wildcard Pattern

The wildcard pattern (_) always succeeds and binds no name:

Sequence Patterns

A sequence pattern contains several subpatterns to be matched against sequence elements:

Mapping Patterns

A mapping pattern contains one or more key-value patterns:

Class Patterns

A class pattern represents a class and its positional and keyword arguments:

OR Patterns

An OR pattern is two or more patterns separated by vertical bars:

Guards

A guard is an additional condition that must succeed for code inside the case block to execute:

Function Definitions

A function definition defines a user-defined function object:
A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object:

Parameters

identifier
A simple parameter name.
default
A parameter with a default value.
varargs
A parameter that receives excess positional arguments as a tuple.
kwargs
A parameter that receives excess keyword arguments as a dictionary.
Example with all parameter types:

Annotations

Parameters may have an annotation of the form : expression following the parameter name. Functions may have “return” annotation of the form -> expression after the parameter list:

Decorators

A function definition may be wrapped by one or more decorator expressions:

Class Definitions

A class definition defines a class object:
A class definition is an executable statement. The inheritance list usually gives a list of base classes:

Class Attributes

The class’s suite is then executed in a new execution frame. When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary:

Generic Classes

A list of type parameters may be given in square brackets between the class’s name and its base classes: