python3.14 script.py★Run a file with the 3.14 interpreter.python3.14★Open the REPL — now with syntax colour & import autocomplete.python -m venv .venv★Create an isolated virtual environment.source .venv/bin/activateActivate it (.venv\Scripts\activateon Windows).python -m pip install rich★Install a package into the active env.python -c "print(1+1)"Run a one-liner (auto-dedented in 3.14).python -m moduleRun a module as a script (e.g.http.server).
x = 42★Assignment binds a name to an object — no declaration.a, b = 1, 2★Tuple unpacking;a, *rest = seqgrabs the tail.x = y = 0Chained assignment — both names to one object.type(x) · isinstance(x, int)Inspect / test an object's type.int float complex bool strCore scalars;3+4jis complex,True/Falseare ints.v = NoneThe null singleton — test withis None.if (n := len(a)) > 10:Walrus:=assigns inside an expression.
+ - * / # / always gives a floatArithmetic;/returns float even for ints.// % **★Floor-divide, modulo, power (2**10→ 1024).== != < <= > >=Comparison — chainable:0 <= x < 10.and or not★Boolean ops; short-circuit & return an operand.x is y · x is not yIdentity — same object? Use forNone, not equality.k in seq · k not in seq★Membership test on any container.a if cond else b★Conditional (ternary) expression.
s = "hi" · 'hi' · """multi"""Any quote style; triple quotes span lines.f"{name} is {age}"★f-string interpolation — the default way to format.f"{x=}" · f"{x:.2f}" · f"{x:,}"★Self-docx=…, 2 decimals, thousands separators.s[0] · s[1:4] · s[::-1]★Index & slice;[::-1]reverses..strip() .lower() .replace(a,b)Return new strings — the original never mutates..split(sep) · ",".join(parts)★Split to list; join an iterable back to a string..startswith() .find() f"{v!r}"Prefix test, index-of,!rfor the repr form.
xs = [1, 2, 3]★Ordered, mutable, mixed-type sequence.xs[0] · xs[-1] · xs[1:3]★Index from front / back; slice returns a new list..append(v) · .extend(it)★Add one item / splice in many..insert(i,v) .pop(i) .remove(v)Insert at index; pop/return; delete first match..sort() · sorted(xs, reverse=True)★.sort()mutates in place;sorted()returns new.[x*2 for x in xs if x>0]★List comprehension — build & filter in one line.len(xs) sum(xs) min(xs) max(xs)Common aggregate built-ins.
t = (1, 2) · single = (1,)★Immutable sequence; the comma makes the tuple.x, y, z = tUnpack — great for multiple returns & swaps.st = {1, 2, 3} · set()★Unordered, unique;set()for an empty one ({}is a dict).a | b · a & b · a - b · a ^ bUnion · intersection · difference · symmetric-diff..add(v) · .discard(v)Insert; remove without error if absent.v in st★O(1) membership — the reason to reach for a set.frozenset(xs)Immutable set — hashable, usable as a dict key.
d = {"a": 1, "b": 2}★Insertion-ordered map (guaranteed since 3.7).d["a"] · d.get("z", 0)★Index raises on miss;.getreturns a default.d["c"] = 3 · .setdefault(k, [])Assign; get-or-create in one step.for k, v in d.items():★Iterate pairs; also.keys()/.values().d1 | d2 · d1 |= d2★Merge into a new dict / update in place.{k: v for k, v in pairs}Dict comprehension..pop(k) · del d[k] · k in dRemove & return; delete; test a key.
if c: … elif d: … else: …★Branching; blocks are defined by indentation.for item in iterable:★Iterate any sequence, range, or generator.while cond:Loop until the condition is falsy.break · continue · pass★Exit loop · skip to next · do-nothing placeholder.for … else:elseruns only if the loop wasn'tbreak-ed.with open(f) as fh:★Context manager — auto-cleanup on exit.assert cond, "msg"Sanity check; stripped away under-O.
match command.split():★Structural pattern matching on shape, not just value.case ["go", direction]:Match a sequence & capture parts into names.case Point(x=0, y=y):Class pattern — destructure attributes.case n if n > 0:Guard — extra boolean condition on a pattern.case 1 | 2 | 3:Or-pattern — match any of several literals.case _:★Wildcard — the default / catch-all arm.
[f(x) for x in xs]★List comp — the idiomatic map+filter.{x for x in xs} · {k: v for …}Set & dict comprehensions.(x*x for x in xs)★Generator expression — lazy, memory-light.def gen(): yield v★A function withyieldis a generator.yield from otherDelegate to a sub-iterable / sub-generator.next(g) · list(g)Pull one value / drain the whole generator.
def f(a, b=1): return a+b★Positional args with defaults (defaults eval once!).f(*args, **kwargs)★Collect extra positionals / keywords; also splat to call.def f(a, *, key):*forceskeyto be keyword-only.def f(a, /, b):/makesapositional-only.lambda x: x + 1★Anonymous one-expression function.def f(x: int) -> str:Type hints — lazy in 3.14, no quoting needed. 3.14global g · nonlocal nRebind an outer-scope name from inside.
enumerate(xs, start=1)★Index + item together — beats manual counters.zip(a, b) · zip(a, b, strict=True)★Walk sequences in lockstep; strict checks equal length.sorted(xs, key=lambda r: r.age)★Sort by a computed key; addreverse=True.range(start, stop, step)★Lazy integer sequence — stop is exclusive.reversed(xs) · map(f, xs, strict=…)Reverse iterator;mapgainsstrictin 3.14. 3.14any(xs) · all(xs)★Short-circuit truth tests over an iterable.
class Dog: …★Define a new type; instances viaDog().def __init__(self, name):★Constructor;selfis the instance, always first.self.name = nameInstance attribute set in the initializer.class Pup(Dog): super().__init__(…)Inheritance;super()calls the parent.@property★Expose a method as a read-only attribute.@classmethod · @staticmethodBind to the class / to nothing (noself).__repr__ __eq__ __len__Dunder methods hook into built-in behaviour.
from dataclasses import dataclass★Auto-generates__init__,__repr__,__eq__.@dataclass★
class Point: x: int; y: intFields are just annotated class attributes.tags: list = field(default_factory=list)Use a factory for mutable defaults — never= [].@dataclass(frozen=True)Immutable & hashable instances.@dataclass(slots=True)Slot layout — less memory, faster attribute access.
import math★Import a module; use asmath.sqrt(2).from math import sqrt, pi★Bring specific names into scope.import numpy as np★Alias a long module name.from . import siblingRelative import inside a package.if __name__ == "__main__":★Run this block only when executed directly.dir(mod) · help(obj)Explore a module's names / read its docs.
try: … except ValueError as e:★Catch a type; bind the instance withas.except TypeError, ValueError:3.14No brackets needed for multiple types (noas).else: … · finally: …else= no error;finallyalways runs.raise ValueError("bad")★Signal an error; bareraisere-raises.raise E(…) from causeChain exceptions to preserve the root cause.except* TypeError:Handle one type from anExceptionGroup.except: # bare — avoidavoidSwallows everything incl.KeyboardInterrupt.
with open(p) as f: f.read()★withcloses the file even on error.with open(p, "w") as f: f.write(s)★Modes:rread ·wwrite ·aappend ·bbinary.for line in f:Stream a file line-by-line, no full load.from pathlib import Path★Object paths:Path("a") / "b.txt".p.read_text() · p.write_text(s)One-shot text I/O without an explicit handle.p.copy(dst) · p.move(dst)3.14Pathgains recursive copy/move (&*_into).
name: str · count: int = 0★Annotate variables & attributes.list[int] · dict[str, int]★Built-in generics — notyping.Listneeded.x: int | None★Modern union;| NonereplacesOptional[int].from typing import Callable, AnyCallable[[int], str],Any,Literal,TypedDict.def f(n: Node): # no quotes3.14Deferred eval — forward refs work unquoted.$ pip install mypy; mypy app.pyHints are ignored at runtime — a checker enforces them.
collections★Counter,defaultdict,deque,namedtuple.itertools★chain,groupby,product,combinations,count.functoolscache,reduce,partial,wraps,Placeholder. 3.14pathlib · os · sys · shutil★Paths, environment, argv, high-level file ops.json · re · datetime★Parse/dump JSON, regex, dates & times.random · math · statisticsRandomness, numeric functions, mean/median/stdev.compression.zstd3.14Zstandard compress/decompress in the stdlib.