A statement is the unit of execution. A simple statement fits on one logical
line. A compound statement contains other statements. This page follows
chapters 7 and 8 of the Language Reference. The match statement has its own
page, Match.
Forms of statement
statement: stmt_list NEWLINE | compound_stmt
stmt_list: simple_stmt (";" simple_stmt)* [";"]
suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | match_stmt
| funcdef | classdef | async_with_stmt | async_for_stmt | async_funcdef
Simple statements on one line are separated by semicolons. A compound statement has a
header ending in a colon and a suite, either an indented block or simple
statements on the same line. A suite on the header's line cannot itself be compound,
so if a: if b: c is an error.
| Simple statements | Compound statements |
|---|---|
Expression, assignment, assert, pass, del, return, yield, raise, break, continue, import, global, nonlocal, type | if, while, for, try, with, match, def, class, async def, async for, async with |
Expression statements
An expression can be used as a statement, normally to call a function for its effect
(7.1). The value is discarded, except at the interactive prompt, which prints it unless
it is None.
Assignment
assignment_stmt: (target_list "=")+ (starred_expression | yield_expression)
target_list: target ("," target)* [","]
target: identifier | "(" [target_list] ")" | "[" [target_list] "]"
| attributeref | subscription | "*" target
The right-hand side is evaluated first, once. The result is then assigned to each target list from left to right (7.2).
| Target | Effect |
|---|---|
| Name | Binds the name in the current scope, or as declared by global or nonlocal |
Attribute, a.b | Calls __setattr__ |
Subscription, a[i] | Calls __setitem__ |
| List of targets | Unpacks the value, which must have a matching length |
*name in a list | Collects the rest into a list. At most one per list |
a = b = [] # one list, two names
x, y = 1, 2 # unpacking
x, y = y, x # swap
first, *rest = [1, 2, 3] # 1, [2, 3]
[p, *q, r] = 1, 2, 3, 4 # 1, [2, 3], 4
*a, = 1, 2 # [1, 2]
(a, b), c = (1, 2), 3 # nested
i = 0
x = [0, 0]
i, x[i] = 1, 2 # i becomes 1 first, so x[1] is set
x # [0, 2]
A starred name must be inside a list or tuple of targets, so *a = 1, 2 is
an error. A length mismatch raises ValueError.
Augmented assignment
augmented_assignment_stmt: augtarget augop (expression_list | yield_expression)
augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
x += 1 evaluates the target once and, where possible, changes the
object in place (7.2.1). The target must be a single name, attribute or item. A
list is changed in place, while an immutable object is replaced:
c = [1, 2]
d = c
d += [3]
c # [1, 2, 3]: same list
e = (1,)
f = e
f += (2,)
e # (1,): f is a new tuple
t = ([1],)
t[0] += [2] # TypeError, yet t is now ([1, 2],)
Annotated assignment
annotated_assignment_stmt: augtarget ":" expression
["=" (starred_expression | yield_expression)]
x: int = 1 binds x and records its
annotation (7.2.2, PEP 526,
Python 3.6). Without a value, x: int records the annotation and binds
nothing. It still makes x local to a function. Only a single target may
be annotated. Annotations of local variables are never evaluated or stored.
Other simple statements
pass
pass does nothing, and fills a place where a statement is required
(7.4). ... is often used in the same way in stubs.
del
del_stmt: "del" target_list
del deletes each target from left to right (7.5). For a name it removes
the binding; for an attribute or item it calls __delattr__ or
__delitem__. del s[i:j] deletes a slice. Deleting a name that
is not bound raises NameError. The object is destroyed only when nothing
else refers to it.
assert
assert_stmt: "assert" expression ["," expression]
A debugging check (7.3). assert x, y is equivalent to the following.
Under -O, __debug__ is false and no code is generated.
if __debug__:
if not x:
raise AssertionError(y)
assert x, yWriting assert (x, "message") asserts a non-empty tuple, which is
always true. The compiler warns about it with a SyntaxWarning.
return
return_stmt: "return" [expression_list]
Ends a function and returns a value, or None (7.6). It is valid only in
a function. A finally clause runs before the function exits. In a
generator, the value becomes StopIteration.value. In an asynchronous
generator return with a value is a SyntaxError.
break and continue
break ends the nearest enclosing for or
while loop, and skips its else clause (7.9).
continue starts its next iteration (7.10). Each may appear only inside a
loop, not inside a function or class nested in the loop.
import, global, nonlocal, raise and yield
These are covered on their own pages:
import,
global and
nonlocal,
raise, and
yield.
The type statement
type_stmt: 'type' identifier [type_params] "=" expression
Declares a type alias (7.14, PEP 695, Python 3.12). The name is bound to a
typing.TypeAliasType. Its value is
lazily evaluated,
so an alias can refer to itself or to a name defined later. type is a
soft keyword, so it is still valid as a name.
type Point = tuple[float, float]
type ListOrSet[T] = list[T] | set[T]
Point.__value__ # tuple[float, float]
if
if_stmt: "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
The conditions are tested in order until one is true, and that suite runs (8.1). If
none is true, the else suite runs when present.
while
while_stmt: "while" assignment_expression ":" suite ["else" ":" suite]
Repeats while the condition is true (8.2). The else suite runs once the
condition is false. A break skips it.
for
for_stmt: "for" target_list "in" starred_expression_list ":" suite
["else" ":" suite]
Iterates over any iterable and assigns each item to the targets (8.3). The list is evaluated once, and starred items are allowed since Python 3.11.
- The loop's
elsesuite runs when the items are used up. Abreakskips it. - The targets stay bound after the loop, to the last value. If there were no items, they are not bound at all.
- Assigning to a target in the body does not affect the next item.
- A list changed while it is being looped over can skip or repeat items, so loop over
a copy. Changing a dictionary's size during iteration raises
RuntimeError.
for n in numbers:
if n < 0:
print("found", n)
break
else:
print("no negative numbers")
else runs only when the loop ends without breakwith
with_stmt: "with" ( "(" with_stmt_contents ","? ")" | with_stmt_contents ) ":" suite
with_stmt_contents: with_item ("," with_item)*
with_item: expression ["as" target]
Wraps a suite in a context manager, whose __exit__ runs however
the suite ends (8.5, PEP 343). A single item behaves like this code, with special method
lookup on the type:
manager = EXPRESSION
enter = manager.__enter__
exit = manager.__exit__
value = enter()
hit_except = False
try:
TARGET = value
SUITE
except:
hit_except = True
if not exit(*sys.exc_info()):
raise
finally:
if not hit_except:
exit(None, None, None)
with EXPRESSION as TARGET: SUITEIf __exit__ returns a true value, the exception is suppressed. Several
items behave like nested with statements. Parentheses around the items,
with a trailing comma, are allowed since Python 3.10. The contextlib
module helps write context managers.
with (
open("in.txt") as source,
open("out.txt", "w") as target,
):
target.write(source.read())
try
try_stmt: try1_stmt | try2_stmt | try3_stmt
try1_stmt: "try" ":" suite
("except" [expression ["as" identifier]] ":" suite)+
["else" ":" suite]
["finally" ":" suite]
try2_stmt: "try" ":" suite
("except" "*" expression ["as" identifier] ":" suite)+
["else" ":" suite]
["finally" ":" suite]
try3_stmt: "try" ":" suite
"finally" ":" suite
The try suite runs first. On an exception, the handlers are checked in
order, and the first match runs (8.4). The else suite runs if the
try suite finishes with no exception. The finally suite always
runs last. What each form catches is on
Exceptions.
- A
return,breakorcontinueinside afinallydiscards any exception in flight, and replaces any earlierreturnvalue. The compiler gives aSyntaxWarningfor these since Python 3.14 (PEP 765). finallyruns on the way out, soreturnin thetrysuite runs thefinallysuite before returning.- A
trystatement cannot mixexceptandexcept*clauses.
Definitions
def and class are statements as well, covered on
Functions and
Classes. The asynchronous forms are on
Generators and async.