Skip to main content

Developer reference

Python Cheatsheet: Syntax, Collections, Files, and OOP

A practical Python reference for data transformations, clear function contracts, safe resource handling, simple object models, and debugging.

Pythonbeginner4 min readProgramming reference

Learning overview

Estimated time
4 minutes
Difficulty
Beginner
Prerequisites
No prior experience required
Learning outcome
Explain python using a clear mental model · Apply python in practical Python work
Last updated
July 18, 2026

Values and collections

Choose collections by mutability, order, uniqueness, and lookup requirements. Use comprehensions for simple readable transformations.

collections.py
lessons = [
    {"title": "Variables", "complete": True},
    {"title": "Lists", "complete": False},
]

remaining = [lesson for lesson in lessons if not lesson["complete"]]
titles = {lesson["title"] for lesson in lessons}
by_title = {lesson["title"]: lesson for lesson in lessons}

Functions and typing

Use explicit parameters, return values, and None defaults for optional mutable inputs. Type hints document contracts and support tooling but do not enforce types at runtime by themselves.

functions.py
def completion_percent(completed: int, total: int) -> int:
    """Return a whole-number completion percentage."""
    if total <= 0:
        return 0
    return round(completed / total * 100)

Iteration patterns

Iterate directly, use enumerate for positions, zip aligned sequences, and generators when values can be produced lazily.

iteration.py
for index, lesson in enumerate(lessons, start=1):
    print(index, lesson["title"])

squares = (number * number for number in range(1_000_000))
first_ten = [next(squares) for _ in range(10)]

Exceptions and files

Catch expected exceptions narrowly, preserve error context, and use context managers so resources close even when work fails.

files.py
import json
from pathlib import Path


def load_config(path: Path) -> dict:
    try:
        with path.open(encoding="utf-8") as file:
            return json.load(file)
    except json.JSONDecodeError as error:
        raise ValueError(f"Invalid JSON in {path}") from error

Dataclasses and testing

Use a dataclass for a record with generated initialization and representation. Prefer composition over deep inheritance and test observable behavior.

models.py
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Expense:
    category: str
    amount: Decimal


def test_expense_preserves_decimal_amount():
    expense = Expense("Food", Decimal("9.50"))
    assert expense.amount == Decimal("9.50")

Frequently asked questions

Which Python version does this cheatsheet target?

It uses modern Python 3 syntax. Check your project’s supported versions before using newer typing or standard-library features.

Do Python type hints change runtime behavior?

Usually no. They are metadata used by readers and tools unless a framework or runtime validator explicitly interprets them.

Topic graph

A taxonomy-generated path through this subject.

  1. Python
  2. Programming reference
  3. python
  4. reference
  5. typing
  6. file-handling
  7. What Is Python in Programming?
  8. Learn Python: From Fundamentals to Real Applications
  9. Python Tutorial: Build a Command-Line Expense Tracker

Recommended automatically from shared technologies, topics, intent, and difficulty.

Hand-picked companion pages that deepen this topic.

Your next steps

Continue learning

  1. 1glossaryWhat Is Python in Programming?
  2. 2guidesLearn Python: From Fundamentals to Real Applications
  3. 3guidesPython Tutorial: Build a Command-Line Expense Tracker
  4. 4cheatsheetsJavaScript Cheatsheet: Syntax, Collections, DOM, Async