This Python cheat sheet focuses on the syntax used in real programs: collections, control flow, functions, exceptions, files, classes, comprehensions, and type hints.
A reference is useful when it helps you recognize a pattern and return to the problem. Keep the examples small, then write tests around the behavior that matters.
Table of contents
- Values and collections
- Control flow and iteration
- Functions and data boundaries
- Comprehensions, generators, and exceptions
- Files, resources, classes, and typing
- How this fits the rest of the stack
- FAQ
Values and collections
name = "api"
retries = 3
enabled = True
tags = ["prod", "web"]
ports = {80, 443}
service = {"name": name, "port": 8000}
point = (10, 20)
Lists are ordered and mutable, tuples are ordered and fixed-shape, sets hold unique hashable values, and dictionaries map keys to values. Use explicit names over compressed one-letter variables outside tiny loops. None represents absence, but domain models often deserve a more precise type or state than a nullable value.
Control flow and iteration
for service in services:
if not service.enabled:
continue
deploy(service)
else:
print("processed every service")
status = "ready" if healthy else "blocked"
Use enumerate when you need positions and zip when walking collections together. Iterating directly over values is clearer than indexing by default. The loop else branch runs when the loop completes without break, which is powerful but unfamiliar; use it only when it makes the search logic clearer.
Functions and data boundaries
def connect(host: str, *, timeout: float = 5.0) -> bool:
"""Connect to a service within the timeout."""
return probe(host, timeout=timeout)
result = connect("db.internal", timeout=2.5)
Keyword-only parameters make call sites readable and protect APIs as they grow. Avoid mutable default arguments such as an empty list; create them inside the function. Return one coherent value, a typed data object, or raise a meaningful exception instead of mixing several unrelated return shapes.
Comprehensions, generators, and exceptions
active = [s.name for s in services if s.enabled]
by_name = {s.name: s for s in services}
lines = (line.strip() for line in handle if line.strip())
try:
config = load_config(path)
except FileNotFoundError as exc:
raise ConfigError(f"missing config: {path}") from exc
Comprehensions are excellent for one transformation and one filter. When logic gains branching or side effects, use a normal loop. Catch the narrow exception you can handle, preserve the original cause, and avoid broad except clauses that turn programming bugs into silent defaults.
Files, resources, classes, and typing
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Service:
name: str
port: int
text = Path("config.txt").read_text(encoding="utf-8")
services: list[Service] = [Service("api", 8000)]
Context managers close files and release resources reliably. pathlib keeps path operations portable. Dataclasses are a concise fit for data-bearing objects; regular classes earn their place when behavior and invariants belong together. Type hints support editors, review, and static checking but do not replace runtime validation at network and file boundaries.
Format with an automated tool, lint in CI, isolate dependencies in a virtual environment, and write focused tests. Python’s readable syntax is an advantage only when the project keeps its data flow and failure behavior equally readable.
Modern Python also rewards a few project-level habits that do not fit in one syntax example. Use pyproject.toml as the central tool configuration, pin deployable dependencies through a lock or constraints workflow, and separate library code from command-line entry points. Prefer logging over print for long-running services, and include context without recording secrets. Use async only when the surrounding libraries and workload benefit from concurrent waiting; it does not make CPU-heavy code faster. Profile before optimizing, and choose a clear ordinary loop over a compressed expression when the loop is easier to debug. The language gives you several ways to express the same operation. Consistency is what lets a team read it quickly.
How this fits the rest of the stack
A Python program becomes a service when it needs runtime, secrets, storage, and logs. The RunxBuild hosting calculator shows those line items together, and the RunxBuild dashboard provides a deployment path for the application.
Useful related references:
- Python Not Equal: != vs is not, and Why the Difference Bites
- Python Integer Division: Why // Floors and Why -7 // 2 Is -4
- The Python return Statement: What It Does, and What None Tells You
- Python services on RunxBuild
FAQ
What collections should a Python beginner learn first?
Learn lists, dictionaries, sets, and tuples, including mutability and the requirement that dictionary keys and set elements be hashable.
Why are mutable default arguments risky?
The same object is reused across calls, so state can leak. Use None and create a new list or dictionary inside the function.
When should I use a comprehension?
Use it for a clear transformation and optional filter. Switch to a loop when logic has branches, error handling, or side effects.
Do Python type hints enforce types at runtime?
Not by themselves. They support tools and documentation; validate untrusted runtime data separately.
What is the best way to open a file?
Use a context manager or pathlib convenience method, specify encoding for text, and handle expected filesystem errors.