if / elif / else
negative
zero
positivepass
pass does nothing. Use it where the grammar requires a block.
donewhile
15while … else
The else runs when the loop ends without break.
loop finished cleanlyfor
for iterates any iterable: list, tuple, dict, set, range, string, or generator.
a
b
ca 1
b 2
c 31 [2, 3]
4 [5, 6, 7]break and continue
break exits the loop. continue skips to the next item. Both work in for and while.
1
3for … else
The else runs when the loop exhausts its iterator without break.
donematch / case
Supported patterns: literals (int, float, str, True, False, None, and negative numbers), capture names, the _ wildcard, OR patterns with |, guards with if, and sequence patterns with an optional *rest.
Items in a sequence pattern must be literals, capture names, or _. Nested sequence patterns, mapping patterns, class patterns, and as captures do not parse. Use chained if and elif for those. A sequence pattern matches only list and tuple subjects. Any other value, including str and bytes, fails the pattern and falls through to the next case.
zero small negative otherempty
single 5
pair-equal
1 then 3 moretry / except / else / finally
5.0
NoneA handler names one exception, a tuple of exceptions, or nothing. A bare except catches everything. else runs when the try body raised nothing. finally always runs.
parsed 42
cleanupcaughtHandlers match subclasses. except Exception catches ValueError, RuntimeError, KeyError, and the rest of the hierarchy listed in Limits and errors.
subclass caughtraise
rejectedA bare raise inside an except block re-raises the exception being handled.
logging
outer badraise X from Y raises X. The from clause parses and Y evaluates, but the cause is not preserved. There is no __cause__ or __context__. Only X reaches the handler.
caught the ValueErrorwith
with runs the context manager protocol:
- Evaluate the expression.
- Call
__enter__and bind its result to theastarget. - On exit, call
__exit__(exc_type, exc_value, traceback).
On a clean exit the three arguments are None. On an exception they carry the exception info. A truthy return from __exit__ suppresses the exception.
acquire
handle
release
afterMultiple targets:
first secondsuppressedCleanup on early exit
finally and __exit__ run on every way out of a block. That includes normal completion, exceptions, return, break, and continue. A return or break inside finally replaces the original exit.
released
10
released
negative
tick 0
tick 1assert
0.25A failed assertion raises AssertionError. The message after the comma evaluates only on failure and becomes the exception argument (e.args).
math brokedel
del removes a binding. It works on plain names, attributes (del obj.attr), indexed positions (del seq[i]), and parenthesized groups (del (a, b)).
gone
[1, 3]