Syntax, types and control flow
The core language on one page: literals and types, operators, truthiness, conversion, numbers (int, float, Decimal, Fraction), None, and every control-flow form from if to match and comprehensions. Every runnable block is checked against its output on Python 3.13.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| check a type | isinstance(x, T) (a tuple of types also works) |
isinstance(3, (int, float)) → True |
| see the exact type | type(x) |
type(1e3) → float |
| write a big number readably | underscores in the literal | 1_000_000 |
| write binary, octal or hex | 0b, 0o, 0x |
0xFF → 255 |
| parse text in any base | int(text, base) |
int("ff", 16) → 255 |
| show a number in binary or hex | bin(), hex(), f"{n:08b}" |
f"{5:08b}" → 00000101 |
| divide and drop the remainder | // (floors toward minus infinity) |
-7 // 2 → -4 |
| get quotient and remainder | divmod(a, b) |
divmod(555, 60) → (9, 15) |
| round to n decimals | round(x, n) (halves go to even) |
round(2.5) → 2 |
| round halves up (money) | Decimal.quantize(..., ROUND_HALF_UP) |
see Numbers |
| floor, ceil, truncate | math.floor, math.ceil, math.trunc |
math.ceil(2.1) → 3 |
| compare floats | math.isclose(a, b) |
math.isclose(0.1 + 0.2, 0.3) → True |
| exact decimal arithmetic | Decimal("0.10") (from a string) |
Decimal("0.1") + Decimal("0.2") |
| exact fractions | Fraction(1, 3) |
Fraction(1, 3) * 3 → 1 |
| infinity and NaN | math.inf, math.nan, math.isnan(x) |
math.isnan(float("nan")) |
| test for a missing value | x is None |
if reading is None: |
give a default for None only |
x if x is not None else default |
0 stays 0 |
| give a default for any falsy value | x or default |
"" or "n/a" → 'n/a' |
| test a range | chained comparison | 0 <= x < 10 |
| test membership | in |
"a" in "cat", k in d |
| assign inside an expression | walrus := |
while (line := f.readline()): |
| choose between two values | conditional expression | "odd" if n % 2 else "even" |
| branch on the shape of data | match / case |
see match |
| loop with an index | enumerate(seq, start=1) |
for i, x in enumerate(xs, 1): |
| loop over two sequences together | zip(a, b, strict=True) |
fails if lengths differ |
| loop backward | reversed(seq) or range(n - 1, -1, -1) |
for x in reversed(xs): |
run code when a loop did not break |
for ... else |
search loops |
| skip to the next iteration | continue |
|
| build a list from a loop | list comprehension | [x * 2 for x in xs if x > 0] |
| do nothing in a block | pass or ... |
def todo(): ... |
| swap two variables | tuple assignment | a, b = b, a |
| unpack “first and the rest” | star target | first, *rest = items |
| run code only when the file is run as a script | if __name__ == "__main__": |
not on import |
Literals
Section titled “Literals”| Type | Literal forms | Notes |
|---|---|---|
int |
42, -7, 1_000_000, 0b1010, 0o17, 0xFF |
arbitrary precision; no long |
float |
3.14, .5, 2., 1e-3, 6.02e23, 1_000.5 |
IEEE 754 double, about 15–17 significant digits |
complex |
2j, 1 + 2j |
.real, .imag, abs(z) |
bool |
True, False |
a subclass of int: True + True == 2 |
str |
'a', "a", """multi-line""", r"C:\path", f"{x}" |
immutable Unicode text |
bytes |
b"raw", rb"\d" |
immutable bytes (ASCII in the literal) |
NoneType |
None |
the only value of its type |
list |
[], [1, 2], [1, 2,] |
trailing comma allowed |
tuple |
(), (1,), 1, 2 |
the comma makes the tuple, not the parentheses |
dict |
{}, {"a": 1}, {**d, "b": 2} |
{} is an empty dict |
set |
{1, 2}, set() |
there is no empty-set literal |
range |
range(5), range(1, 10, 2) |
lazy, immutable sequence |
Ellipsis |
... |
placeholder body, NumPy slicing |
Built-in types at a glance
Section titled “Built-in types at a glance”| Type | Mutable | Hashable (dict key) | Ordered | Duplicates | Typical use |
|---|---|---|---|---|---|
int, float, bool, complex |
no | yes | — | — | numbers, flags |
str, bytes |
no | yes | yes | yes | text, raw data |
tuple |
no | yes, if all items are | yes | yes | records, dict keys |
frozenset |
no | yes | no | no | set as a dict key |
list |
yes | no | yes | yes | ordered collections |
dict |
yes | no | insertion order | unique keys | lookups by key |
set |
yes | no | no | no | membership, dedupe |
bytearray |
yes | no | yes | yes | editable bytes |
NoneType |
no | yes | — | — | “no value” |
values = [7, 7.0, 7j, True, None, (), (1,), {}, set(), b"", range(3)]print([type(v).__name__ for v in values])print(isinstance(True, int), isinstance(3, (int, float)), issubclass(bool, int))['int', 'float', 'complex', 'bool', 'NoneType', 'tuple', 'tuple', 'dict', 'set', 'bytes', 'range']True True TrueNames and assignment
Section titled “Names and assignment”| Form | Example | Meaning |
|---|---|---|
| simple | x = 1 |
bind the name x to the object 1 |
| multiple | a, b = 1, 2 |
tuple unpacking |
| swap | a, b = b, a |
right side is built first |
| chained | a = b = [] |
both names point to the same list |
| augmented | x += 1, s *= 2, n //= 3 |
in place for mutable objects (list += mutates) |
| star unpacking | first, *middle, last = seq |
middle is always a list |
| nested unpacking | (a, b), c = (1, 2), 3 |
shapes must match |
| walrus | if (n := len(xs)) > 3: |
assign and use in one expression (3.8+) |
| annotated | count: int = 0 |
type hint, not enforced at run time |
| delete | del x, del xs[0], del d["k"] |
remove a name, an item or a key |
first, *middle, last = [10, 20, 30, 40]a = b = [] # one list, two namesa.append(1)x, y = 1, 2x, y = y, xprint(first, middle, last, b, x, y)if (n := len(middle)) >= 2: print(f"{n} items in the middle")10 [20, 30] 40 [1] 2 12 items in the middleOperators
Section titled “Operators”| Group | Operators | Example | Result |
|---|---|---|---|
| arithmetic | + - * / // % ** |
7 / 2, 7 // 2, 7 % 2, 2 ** 10 |
3.5, 3, 1, 1024 |
| matrix multiply | @ |
a @ b (NumPy) |
|
| comparison | == != < <= > >= |
1 < 2 < 3 |
True (chained) |
| identity | is, is not |
x is None |
same object |
| membership | in, not in |
3 in [1, 2, 3] |
True |
| logical | and, or, not |
0 or 5 |
5 (returns an operand) |
| bitwise | & | ^ ~ << >> |
6 & 3, 6 | 3, 6 ^ 3, ~6, 1 << 4 |
2, 7, 5, -7, 16 |
| conditional | a if cond else b |
"pos" if x > 0 else "neg" |
|
| assignment expression | := |
(n := 10) + 1 |
11 |
| set operators | | & - ^ |
{1, 2} | {2, 3} |
{1, 2, 3} |
| dict merge | |, |= |
{"a": 1} | {"b": 2} |
right side wins on clashes |
| sequence | +, * |
[0] * 3, "ab" + "c" |
[0, 0, 0], 'abc' |
Precedence (highest first)
Section titled “Precedence (highest first)”| Level | Operators | Note |
|---|---|---|
| 1 | (...), [...], {...}, literals |
grouping and displays |
| 2 | x[i], x[a:b], f(...), x.attr |
subscript, slice, call, attribute |
| 3 | await x |
|
| 4 | ** |
right to left: 2 ** 3 ** 2 == 512; binds tighter than unary minus on its left |
| 5 | +x, -x, ~x |
-2 ** 2 == -4 |
| 6 | *, @, /, //, % |
left to right |
| 7 | +, - |
|
| 8 | <<, >> |
|
| 9 | & |
|
| 10 | ^ |
|
| 11 | | |
|
| 12 | in, not in, is, is not, <, <=, >, >=, !=, == |
all chain: a < b == c |
| 13 | not x |
not a == b is not (a == b) |
| 14 | and |
|
| 15 | or |
a or b and c is a or (b and c) |
| 16 | x if c else y |
|
| 17 | lambda |
|
| 18 | := |
lowest; usually needs parentheses |
print(-2 ** 2, (-2) ** 2, 2 ** 3 ** 2, 2 ** -1)print(1 + 2 * 3, (1 + 2) * 3, 10 - 4 - 3, 2 * 3 % 4)print(1 < 2 < 3, 1 < 3 > 2, (1 < 2) < 3, not 1 == 2)x, y = 5, 3print(x > 1 & y < 2, (x > 1) & (y < 2)) # & binds tighter than >print(True or False and False, (True or False) and False)-4 4 512 0.57 9 3 2True True True TrueTrue FalseTrue FalseTruthiness and logical operators
Section titled “Truthiness and logical operators”| Falsy | Truthy |
|---|---|
False, None |
True |
0, 0.0, 0j, Decimal(0), Fraction(0) |
any other number, negatives too |
"", b"" |
any non-empty string: " ", "0", "False" |
[], (), {}, set(), range(0) |
any non-empty container |
objects whose __bool__ returns False or __len__ returns 0 |
other objects (by default) |
| Expression | Returns | Example |
|---|---|---|
a or b |
a if a is truthy, else b |
"" or "n/a" → 'n/a' |
a and b |
a if a is falsy, else b |
[] and 1 → [] |
not a |
always a bool |
not [] → True |
any(it) |
True if one item is truthy (stops early) |
any(x > 3 for x in xs) |
all(it) |
True if every item is truthy; True for empty |
all([]) → True |
print(bool(0.0), bool("0"), bool([]), bool([0]), bool(None))print(0 or "default", "set" or "default", [] and "never", 3 and 4)print(any([0, "", None]), all([1, "a", [0]]), all([]), any([]))
def check(label): print("checked", label) return False
result = check("a") and check("b") # short-circuit: b is never calledFalse True False True Falsedefault set [] 4False True True Falsechecked aConversion
Section titled “Conversion”| Call | Result | Note |
|---|---|---|
int("42"), int(" 42\n") |
42 |
surrounding whitespace is ignored |
int("1_000") |
1000 |
underscores between digits are allowed |
int("3.7") |
ValueError |
use int(float("3.7")) → 3 |
int(3.7), int(-3.7) |
3, -3 |
truncates toward zero |
int("ff", 16), int("0b101", 0) |
255, 5 |
base 0 reads the prefix |
float("1e-3"), float("inf"), float("nan") |
0.001, inf, nan |
|
float("1,5") |
ValueError |
replace the comma first |
str(3.0), repr("a") |
'3.0', "'a'" |
repr shows quotes and escapes |
bool("False") |
True |
any non-empty string is truthy |
ord("A"), chr(65) |
65, 'A' |
code point ↔ character |
list("abc"), tuple([1, 2]), set([1, 1, 2]) |
['a', 'b', 'c'], (1, 2), {1, 2} |
from any iterable |
dict([("a", 1)]), dict(zip(keys, values)) |
{'a': 1} |
from pairs |
int(True), float(False) |
1, 0.0 |
|
bin(10), oct(10), hex(255) |
'0b1010', '0o12', '0xff' |
strings with prefix |
print(int("ff", 16), int("0o17", 0), int(float("3.7")), int(-3.7))print(float(" 2.5 "), str(1 / 3), repr("tab\t"))print(int("3.7"))255 15 3 -32.5 0.3333333333333333 'tab\t'ValueError: invalid literal for int() with base 10: '3.7'Numbers
Section titled “Numbers”| Type | Use for | Exact? | Create |
|---|---|---|---|
int |
counts, ids, money in cents | yes, any size | 42, int("42") |
float |
measurements, science, ML | no (binary) | 0.1, float("0.1") |
Decimal |
money, fixed decimal places, legal rounding | yes (decimal) | Decimal("0.10") |
Fraction |
exact ratios | yes (rational) | Fraction(1, 3) |
complex |
signals, math | no | 1 + 2j |
from decimal import ROUND_HALF_UP, Decimal, getcontextfrom fractions import Fraction
print(0.1 + 0.2, 0.1 + 0.2 == 0.3) # binary floats are approximateprint(Decimal("0.1") + Decimal("0.2"), Decimal(0.1)) # always build from a stringprice = Decimal("19.99") * 3 * Decimal("0.925")print(price, price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))print(getcontext().prec) # 28 significant digits by defaultprint(Fraction(1, 3) + Fraction(1, 6), Fraction("0.75"))print(Fraction(0.1).limit_denominator(100)) # nearest simple fractionprint(2**100, (2**100).bit_length(), 10**20 // 7) # ints never overflow0.30000000000000004 False0.3 0.100000000000000005551115123125782702118158340454101562555.47225 55.47281/2 3/41/101267650600228229401496703205376 101 14285714285714285714Rounding
Section titled “Rounding”| Call | 2.5 |
-2.5 |
2.675 (to 2 places) |
Rule |
|---|---|---|---|---|
round(x) / round(x, 2) |
2 |
-2 |
2.67 |
half to even, on the binary value |
math.floor(x) |
2 |
-3 |
toward minus infinity | |
math.ceil(x) |
3 |
-2 |
toward plus infinity | |
math.trunc(x), int(x) |
2 |
-2 |
toward zero | |
x // 1 |
2.0 |
-3.0 |
floor, keeps the float type | |
f"{x:.0f}" / f"{x:.2f}" |
'2' |
'-2' |
'2.67' |
same as round |
Decimal(str(x)).quantize(Decimal("0.01"), ROUND_HALF_UP) |
2.68 |
school rounding | ||
round(x, -2) |
to hundreds: round(1250, -2) → 1200 |
import mathfrom decimal import ROUND_HALF_EVEN, ROUND_HALF_UP, Decimal
print([round(x) for x in (0.5, 1.5, 2.5, 3.5)], round(2.675, 2))print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), int(-2.5), -2.5 // 1)cents = Decimal("0.01")for text in ("2.675", "2.665"): d = Decimal(text) print(text, d.quantize(cents, ROUND_HALF_UP), d.quantize(cents, ROUND_HALF_EVEN))print(round(1250, -2), round(1350, -2), round(1234.5678, -1))[0, 2, 2, 4] 2.67-3 -2 -2 -2 -3.02.675 2.68 2.682.665 2.67 2.661200 1400 1230.0Float facts and math helpers
Section titled “Float facts and math helpers”| Task | Use | Example |
|---|---|---|
| compare two floats | math.isclose(a, b, rel_tol=1e-9) |
|
| compare with 0 | math.isclose(x, 0, abs_tol=1e-9) |
relative tolerance alone never matches 0 |
| test NaN | math.isnan(x) (never x == nan) |
nan != nan |
| test infinity | math.isinf(x), math.isfinite(x) |
|
| exactly rounded sum | math.fsum(xs) |
sum() of floats is compensated since 3.12, fsum is exact |
| whole-number float? | x.is_integer() |
(3.0).is_integer() → True |
| integer square root | math.isqrt(n) |
math.isqrt(17) → 4 |
| power with modulus | pow(base, exp, mod) |
fast modular arithmetic |
| gcd, lcm | math.gcd(a, b), math.lcm(a, b) |
|
| product, combinations | math.prod(xs), math.comb(n, k), math.perm(n, k) |
|
| largest float, epsilon | sys.float_info.max, sys.float_info.epsilon |
import math
nan = float("nan")print(nan == nan, math.isnan(nan), math.inf > 1e308, -math.inf < 0)print(0.1 + 0.1 + 0.1, sum([1e100, 1.0, -1e100]), math.fsum([0.1] * 10))print(math.isclose(1e-12, 0), math.isclose(1e-12, 0, abs_tol=1e-9))print(math.isqrt(17), pow(3, 200, 7), math.gcd(12, 18), math.lcm(4, 6), math.comb(5, 2))False True True True0.30000000000000004 1.0 1.0False True4 2 6 12 10| Task | Write | Avoid |
|---|---|---|
test for None |
x is None, x is not None |
x == None (ruff E711) |
| optional parameter | def f(items=None): then if items is None: items = [] |
def f(items=[]): |
default only for None |
value if value is not None else 0 |
value or 0 (also replaces 0, "") |
| type hint | def find(key: str) -> int | None: |
|
function without return |
returns None |
result = xs.sort() (gives None) |
| missing dict key | d.get("k") → None |
d["k"] raises KeyError |
def first_negative(values: list[float]) -> float | None: for v in values: if v < 0: return v return None # explicit: "not found"
found = first_negative([3, 0, 2])print(found, found is None, first_negative([1, -2, -5]))count = 0print(count or 10, count if count is not None else 10) # `or` replaces the real 0print([3, 1, 2].sort()) # in-place methods return NoneNone True -210 0NoneControl flow
Section titled “Control flow”if, elif, else and conditional expressions
Section titled “if, elif, else and conditional expressions”def grade(score: float) -> str: if score >= 90: return "A" elif score >= 75: return "B" elif score >= 50: return "C" else: return "F"
temps = [18.5, 22.0, 25.5]print([grade(s) for s in (95, 75, 49.9)])print(["hot" if t > 24 else "ok" if t >= 19 else "cold" for t in temps])print(max(0, min(100, 120))) # clamp without if['A', 'B', 'F']['cold', 'ok', 'hot']100match-case
Section titled “match-case”| Pattern | Syntax | Matches |
|---|---|---|
| literal | 200, "ok", None, True |
an equal value (None, True, False by identity) |
| or | "a" | "b" |
any alternative |
| wildcard | _ |
anything; binds nothing |
| capture | name |
anything; binds it to name |
| value | Color.RED, http.HTTPStatus.OK |
equal to a dotted constant |
| sequence | [a, b], (a, b, *rest), [] |
any sequence of that length (list, tuple, range, deque), except str, bytes and bytearray |
| mapping | {"type": "click", "x": x, **rest} |
a mapping with these keys; extra keys allowed |
| class | Point(x=0, y=y), Point(0, y), int(n) |
an instance with these attributes |
| as | [*_] as items, (int() | float()) as n |
binds the matched sub-value |
| guard | case [x, y] if x == y: |
the pattern and then the condition |
from dataclasses import dataclass
@dataclassclass Point: x: float y: float
def describe(event: object) -> str: match event: case {"type": "click", "pos": (x, y)}: return f"click at {x},{y}" case {"type": "key", "key": str(key)} if len(key) == 1: return f"key {key!r}" case Point(x=0, y=0): return "origin" case Point(x, y) if x == y: return f"diagonal {x}" case [first, *rest]: return f"list of {1 + len(rest)} starting {first}" case int() | float() as n if n < 0: return f"negative {n}" case None: return "nothing" case _: return f"unknown {type(event).__name__}"
events = [{"type": "click", "pos": (3, 4)}, {"type": "key", "key": "q"}, Point(0, 0), Point(2, 2), [5, 6, 7], -1.5, None, "text"]for e in events: print(describe(e))click at 3,4key 'q'origindiagonal 2list of 3 starting 5negative -1.5nothingunknown strfor, while, break, continue, else
Section titled “for, while, break, continue, else”| Form | Example | Note |
|---|---|---|
| over items | for x in xs: |
any iterable |
| with index | for i, x in enumerate(xs, start=1): |
|
| in parallel | for a, b in zip(xs, ys, strict=True): |
strict=True (3.10+) raises on unequal lengths |
| over a dict | for k, v in d.items(): |
for k in d: gives keys |
| counting | for i in range(start, stop, step): |
stop is excluded |
| backward | for x in reversed(xs): |
|
| sorted | for x in sorted(xs, key=len, reverse=True): |
|
| while | while cond: |
check a condition each pass |
| loop and a half | while True: … if done: break |
|
| read until empty | while (chunk := f.read(4096)): |
walrus |
| skip | continue |
next iteration |
| stop | break |
leaves the innermost loop only |
| no-break branch | for ...: ... else: |
runs if the loop did not break |
range(...) |
Values |
|---|---|
range(5) |
0 1 2 3 4 |
range(2, 6) |
2 3 4 5 |
range(0, 10, 3) |
0 3 6 9 |
range(5, 0, -1) |
5 4 3 2 1 |
range(0), range(5, 2) |
nothing |
for n in [9, 15, 7, 21]: if n % 7 == 0: print("first multiple of 7:", n) breakelse: print("none found")
for i, (name, score) in enumerate(zip(["ana", "ben"], [81, 67], strict=True), start=1): print(i, name, score)
n, steps = 27, 0while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1print("steps:", steps, list(range(10, 0, -3)))first multiple of 7: 71 ana 812 ben 67steps: 111 [10, 7, 4, 1]Comprehension forms
Section titled “Comprehension forms”| Form | Syntax | Result |
|---|---|---|
| list with a filter | [f(x) for x in xs if x > 0] |
if at the end filters |
| choose a value per item | [x if x > 0 else 0 for x in xs] |
if ... else at the front |
| dict, set, generator | {k: v for k, v in pairs}, {x for x in xs}, (x for x in xs) |
Nested loops, flattening, the walrus and the rules of thumb are on the comprehensions section.
Other statements
Section titled “Other statements”| Statement | Use |
|---|---|
pass |
an empty block |
... |
an empty body in stubs and protocols |
assert cond, "message" |
developer checks; removed by python -O |
del name |
unbind a name or remove an item |
global x, nonlocal x |
rebind a name in an outer scope (functions page) |
with ... as f: |
context manager (decorators and context managers) |
try / except / else / finally |
errors (errors and debugging) |
type Alias = int | str |
type alias statement (3.12+) |
if __name__ == "__main__": |
run code only when the file is a script |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
0.1 + 0.2 == 0.3 |
False |
math.isclose; Decimal for money |
round(2.5) |
2, not 3 |
Decimal.quantize(..., ROUND_HALF_UP) |
round(2.675, 2) |
2.67 |
the float is stored as 2.67499...; use Decimal("2.675") |
Decimal(0.1) |
a 55-digit value | build from a string: Decimal("0.1") |
-7 // 2, -7 % 2 |
-4, 1 |
floor division; use math.trunc(a / b) to truncate |
-2 ** 2 |
-4 |
(-2) ** 2 |
x == 1 or 2 |
always truthy | x in (1, 2) |
bool("False") |
True |
compare the text: s.lower() == "true" |
value or default |
replaces a real 0 or "" |
value if value is not None else default |
x == None |
works but is wrong style; breaks with NumPy | x is None |
is with numbers or strings |
a is b can be False for equal values |
use ==; keep is for None, True, False |
(1) |
an int, not a tuple |
(1,) |
{} |
an empty dict, not a set | set() |
a = b = [] |
changing a changes b |
a, b = [], [] |
x > 1 & y < 2 (pandas masks) |
parsed as x > (1 & y) < 2: wrong rows or an error |
(x > 1) & (y < 2) |
nan == nan |
False; nan in checks also mislead |
math.isnan(x) |
case RED: in match |
captures everything; SyntaxError if not last |
use a dotted name Color.RED or a guard |
for ... else |
else runs when the loop did not break |
rename mentally to “nobreak” |
int("1" * 5000) |
ValueError: Exceeds the limit (4300 digits) |
sys.set_int_max_str_digits(0) if you trust the input |
xs = xs.sort() |
xs becomes None |
xs.sort() or xs = sorted(xs) |
zip(a, b) with unequal lengths |
silently drops the extra items | zip(a, b, strict=True) |
True + True |
2 |
bool is an int; check type(x) is bool if it matters |
Learn more
Section titled “Learn more”- 01. Python basics and its cheat sheet
- 03. Control flow and its cheat sheet
- Strings and formatting for f-strings and format specs
- Collections and comprehensions for lists, dicts and sets