python --versionCheck interpreter version.python★Launch the interactive REPL.python script.py★Run a script file.python -m moduleRun a module as a script.python -i script.pyRun then drop into REPL.if __name__ == "__main__":★Guard code that should only run when executed directly.
x = 5★Bind a name to an object (no declaration needed).a, b = b, a★Tuple unpacking — the classic swap.x = y = 0Chained assignment — both names, same object.x += 1★Augmented assignment (also -=, *=, /=, //=, **=).first, *rest = numsExtended (starred) unpacking.if (n := len(data)) > 3:★Walrus operator — assign and use in one expression.
7 / 2★3.5 — true division, always returns float.7 // 2★3 — floor division.7 % 21 — modulo (remainder).2 ** 101024 — exponentiation.x == y x is y★==compares value;iscompares identity.a and b a or b not aBoolean logic; short-circuits and returns an operand, not just True/False.0 < x < 10Chained comparisons work as expected.
f"{name} is {age}"★f-string — fastest, most readable interpolation.f"{value:.2f}"★Format-spec: 2 decimal places.f"{age=}"Debug spec — printsage=2for quick tracing."a b".split()★Split on whitespace → list."-".join(items)★Join an iterable of strings.s.strip() s.replace(a,b)Trim whitespace; substring replace.s.upper() s.lower() s.title()Case transforms.text[1:4] text[::-1]★Slicing — see the reference card for the full notation.
nums.append(x)★Add one item to the end.nums.extend(iterable)Append every item from another iterable.nums.insert(i, x)Insert at a specific index.nums.pop(i)★Remove & return item at index (default: last).nums.remove(x)Remove first matching value (raises if absent).nums.sort(key=fn)★Sort in place;sorted(nums)returns a new list.x in nums len(nums)★Membership test; length.nums.reverse()Reverse in place.
point = (3, 4)★Tuple — ordered, immutable.single = (1,)Trailing comma required for a 1-item tuple.a = {1, 2, 3}★Set — unordered, unique elements.a | b a & b a - b a ^ b★Union · intersection · difference · symmetric difference.frozenset(a)Immutable, hashable set — usable as a dict key.
d = {"a": 1}★Literal mapping.d.get(k, default)★Lookup without raising on a missing key.d.setdefault(k, [])Get, inserting a default if the key is absent.d.pop(k)Remove & return a value.d.items() d.keys() d.values()★Views for iteration.d1 | d2★Merge two dicts (3.9+) — right side wins on conflicts.k in d★Membership test checks keys, not values.
if … elif … else:★Standard branching; colon + indentation define blocks.x if cond else y★Conditional (ternary) expression.match cmd:
case "quit" | "exit":Structural pattern matching (3.10+);case _:is the wildcard.case [x, *rest] if x > 0:Patterns can destructure sequences and add guards.
for x in iterable:★The Python loop — works on anything iterable.for i, x in enumerate(xs):★Index + value together.for a, b in zip(xs, ys):★Walk two iterables in lockstep.while (line := f.readline()):Walrus keeps the read-and-check on one line.break continue★Exit the loop; skip to the next iteration.for … else:elseruns only if the loop finished without abreak.
def f(x, y=1):★Positional param + default value.def f(*args, **kwargs):★Collect extra positional / keyword args.f(*nums, **opts)Unpack a list/dict into a call.def f(a, /, b, *, c):/= positional-only before it;*= keyword-only after.lambda x: x * 2★Anonymous single-expression function.def f(x: int) -> str:Type-hinted signature (not enforced at runtime).
[x*x for x in nums if x > 0]★List comprehension — eager, builds the whole list now.{k: v for k, v in pairs}★Dict comprehension.{x for x in nums}Set comprehension.(x*x for x in nums)★Generator expression — lazy, one value at a time.def gen():★
yield xGenerator function — pauses/resumes at eachyield.yield from other_gen()Delegate iteration to another generator.
class Dog:★
def __init__(self, name):Constructor —selfis the instance, always first param.class Puppy(Dog):★Inheritance; usesuper().__init__()to call the parent.def __repr__(self):★Unambiguous string repr — what you see in the REPL/debugger.def __eq__(self, other):Define value equality (pairs with__hash__).@property
def area(self):Expose a method as a read-only attribute.@classmethod @staticmethodBound to the class, not an instance; static gets no implicit arg.
@dataclass★
class Point:
x: int
y: intAuto-generates__init__,__repr__,__eq__.@dataclass(frozen=True)Makes instances immutable & hashable.field(default_factory=list)Safe default for a mutable field.
@my_decorator★
def f(): …Sugar forf = my_decorator(f).functools.wraps(func)Preserve name/docstring when writing a decorator.with open("f.txt") as f:★withguarantees cleanup even if an exception occurs.@contextmanager
def cm(): yieldTurn a generator into a context manager.
try: … except ValueError as e:★Catch a specific exception type.except (TypeError, KeyError):Catch multiple types in one clause.else: … finally: …★elseruns if no error;finallyalways runs.raise ValueError("msg")★Signal an error explicitly.class MyError(Exception): passCustom exception type.except* ValueError as e:Exception groups (3.11+) — handle one type from a batch of failures.
with open("f.txt") as f:★
data = f.read()Read the whole file.for line in f:★Iterate a file line by line (memory-efficient).f.write(text)Mode"w"overwrites,"a"appends.Path("dir/file.txt")★pathlib— modern, cross-platform path handling.p.exists() p.mkdir(parents=True)Common Path methods.
import module from pkg import x★Import a module or specific names.from pkg import x as yImport with an alias.python -m venv .venv★Create an isolated virtual environment.source .venv/bin/activate★Activate it (Windows:.venv\Scripts\activate).pip install pkg★Install a package into the active environment.pip freeze > requirements.txtSnapshot installed packages.
collections.Counter(items)★Frequency count in one call.collections.defaultdict(list)★Dict with an auto-created default value.itertools.chain(a, b)Iterate several iterables as one.itertools.groupby(data)Group consecutive matching items.functools.lru_cache(maxsize=None)★Memoize a function's results.functools.reduce(fn, iterable)Fold an iterable down to one value.
x: int = 5★Variable annotation.def f(x: int) -> bool:★Parameter & return annotations.list[int] dict[str, int]★Built-in generics (3.9+) — notyping.Listneeded.int | None★Union syntax (3.10+) — replacesOptional[int].
def f(x=[]):gotchaMutable default evaluated once — reused & shared across calls.a is b (for values)gotchaUse==for equality;isonly for identity (e.g.None).rows = [[0]*3]*3gotchaSame inner list repeated 3× — one edit changes every row.[lambda: i for i in range(3)]gotchaLate binding — all three lambdas see the finali.import copy; copy.deepcopy(x)carecopy()is shallow — nested mutables stay shared.
text[0] text[-1]First item; last item.text[1:4]Items at index 1, 2, 3 (stop excluded).text[:3] text[3:]From the start; to the end.text[::2]Every 2nd item.text[::-1]Reversed copy.text[:]Shallow copy of the whole sequence.