if / elif / else
negative
zero
positivewhile
15while … else
The else runs if the loop completes without break.
loop finished cleanlyfor
Iterates anything that produces a sequence: list, tuple, dict, set, range, string, generator.
a
b
ca 1
b 2
c 31 [2, 3]
4 [5, 6, 7]break and continue
1
3for … else
Runs when the loop exhausts its iterator (no break).
donematch / case
Subset supported: literal patterns, capture variables, _ wildcard, OR (|), guards (if), sequence patterns with *rest.
Sequence-pattern items must be literals (int / float / str / True / False / None), capture names, or _. Nested sequences (case [[a, b], c]:), mapping patterns ({"key": x}), class patterns (Point(x=0)), and as captures are unsupported. Use chained if / elif instead. A case [...] pattern matches only a list or tuple subject; any other value (including str / bytes) just fails it and falls through, so scalar and sequence cases mix freely in one match.
Scalars: literals, OR-patterns, capture-with-guard, wildcard.
zero small negative otherSequences: fixed-length patterns, a guard, and a *rest capture.
empty
single 5
pair-equal
1 then 3 morezero
one
many
manytry / except / else / finally
5.0
Nonecleanup
-1caughtraise
rejectedA bare raise inside an except re-raises the exception currently being handled.
logging
outer badraise X from Y raises X. The from clause parses and the cause evaluates, but __cause__ / __context__ aren’t preserved. Only X reaches the handler.
caught the ValueErrorHandlers match on class and declared parents. except Exception catches ValueError, RuntimeError, KeyError, etc:
subclass caughtException names available
Pre-bound exception classes (with their parent links so except <Parent>: matches subclasses) are listed in Limits and errors, Runtime.
with
with drives the context-manager protocol:
- Evaluate the expression.
- Call
__enter__. - Bind the result to
as.
On exit, __exit__(exc_type, exc_value, traceback) runs: (None, None, None) on normal completion, live exception info on raise. A truthy return suppresses the exception; a falsy one propagates it. See /language/dunders.
acquire
handle
release
afterMultiple targets:
first secondCleanup on early exit
finally and __exit__ run on every way out of the block — not only normal completion and exceptions, but also return, break, and continue. A return in a try runs the finally before the value leaves; a break out of a with still calls __exit__. A return or break in the finally itself replaces the original exit.
released
10
released
negative
tick 0
tick 1assert
0.25A failed assertion raises AssertionError. Catch it with except AssertionError, except Exception, or bare except. The optional message after the comma is evaluated only when the assertion fails and becomes the exception’s argument (e.args).
del
Removes a binding from the slot. Works on plain names, attributes (del obj.attr), indexed positions (del seq[i]), and parenthesized target groups (del (a, b)).
gone