Skip to main content

Python Course

Python Cheatsheet

A quick, printable reference with essential Python syntax: variables, strings, lists, dicts, functions, classes, standard library, and common pitfalls. Print to PDF with Ctrl/Cmd + P.

PDF / Print

Save or print this cheatsheet as PDF

Print-ready layout: open in one click and save as PDF from your browser, no account or email required.

0. Core Python Invariants & Pitfalls to Avoid

Five classic sources of silent bugs in Python.

  1. Never use a mutable default argument (def f(xs=[]):) because all calls share it: default to None or field(default_factory=list).
  2. Use is / is not ONLY for None, True, or False; use == for numbers, strings, and value equality.
  3. Remember sort(), append(), and reverse() mutate in-place and return None: use sorted() for a new copy.
  4. Always wrap file handles and external resources in with blocks rather than relying on garbage collection timing.
  5. Type hints are not enforced at runtime by CPython: validate untrusted inputs explicitly or run mypy/pyright.

1. Variables and types

  • Assignment

    x = 10           # int
    pi = 3.14        # float
    name = "Anna"    # str
    active = True    # bool
    empty = None

    Python binds names dynamically to objects without let/var/const keywords.

    Pitfall: Writing b = a aliases the same mutable list; call a.copy() when an independent copy is needed.

  • Types and conversions

    type(42)         # <class 'int'>
    int("42")        # 42
    str(3.14)        # '3.14'
    float("1.5")     # 1.5
    bool(0)          # False

    Explicit type conversions under strong dynamic typing.

    Pitfall: int("3.14") raises ValueError: convert via float() first if the string contains decimals.

  • Comparisons

    1 == 1.0         # True
    1 is 1.0         # False  (identity vs equality)
    None is None     # True   (always use "is" with None)
    "a" in "house"   # True

    Compare values (==), object identity (is), and membership (in).

    Pitfall: Never use == None or compare strings with is: object interning varies across strings.

2. Strings

  • f-string

    name = "World"
    msg = f"Hello, {name}!"
    # Expressions and formatting:
    f"pi = {3.14159:.2f}"   # 'pi = 3.14'
    f"{42:>5}"              # '   42'

    Readable interpolation with format specifiers for precision and padding.

    Pitfall: Literal curly braces inside an f-string must be doubled as {{ and }}.

  • Common methods

    len("hello")             # 5
    "hello".upper()          # 'HELLO'
    "  hello  ".strip()      # 'hello'
    "a,b,c".split(",")       # ['a','b','c']
    "-".join(["a","b","c"])  # 'a-b-c'
    "hello".startswith("he") # True
    "hello".replace("l", "L")

    Immutable string operations always return a new string or list.

    Pitfall: Strings are immutable: calling s.upper() without assigning discards the result.

  • Slicing

    s = "Python"
    s[0]      # 'P'
    s[-1]     # 'n'
    s[1:4]    # 'yth'
    s[:3]     # 'Pyt'
    s[::-1]   # 'nohtyP'

    Extracts substrings with [start:stop:step] where stop is exclusive.

    Pitfall: Out-of-bounds indexing s[99] raises IndexError, whereas out-of-bounds slicing returns "".

3. Numbers and math

  • Operators

    7 // 2     # 3   (integer division)
    7 % 2      # 1   (remainder)
    2 ** 10    # 1024 (exponentiation)
    abs(-5)    # 5
    round(1.6) # 2

    Floor division, modulo, ** exponentiation, and rounding.

    Pitfall: round() uses round-half-to-even (banker’s rounding): round(2.5) returns 2, not 3.

  • Math module

    import math
    math.pi             # 3.141592653589793
    math.sqrt(16)       # 4.0
    math.floor(1.9)     # 1
    math.ceil(1.1)      # 2
    math.log(math.e)    # 1.0

    Standard-library math helpers for floats and logarithms.

    Pitfall: 0.1 + 0.2 != 0.3 in IEEE-754 floats: use math.isclose() or decimal.Decimal for exact currency.

4. Lists

  • Create and access

    a = [1, 2, 3]
    a[0]            # 1
    len(a)          # 3
    a.append(4)     # [1,2,3,4]
    a.pop()         # removes last item
    a[1:3] = [9]    # slice assignment

    Ordered mutable sequences with O(1) index access.

    Pitfall: Mutating a list while iterating over it skips elements or causes subtle index shifts.

  • Comprehensions

    [x * 2 for x in range(5)]              # [0,2,4,6,8]
    [x for x in nums if x > 0]             # filter
    [(x, y) for x in xs for y in ys]       # cartesian product

    Concise syntax for mapping and filtering iterables into lists.

    Pitfall: Use a generator expression (x for x in ...) instead of materializing huge temporary lists.

  • Sorting

    sorted([3, 1, 2])                # [1,2,3]  (copy)
    [3,1,2].sort()                   # in-place
    sorted(users, key=lambda u: u["age"])

    Natural order or custom key extraction (pass reverse=True for descending).

    Pitfall: x = my_list.sort() assigns None to x because .sort() returns None after mutating in-place.

5. Dictionaries

  • Create and access

    u = {"name": "Anna", "age": 30}
    u["name"]            # 'Anna'
    u.get("email", "?")  # default
    u["email"] = "x@y"
    del u["age"]

    Insertion-ordered key-value hash map with O(1) average lookup.

    Pitfall: d["missing"] raises KeyError; use d.get("missing") when a key may be absent.

  • Iteration

    for k in u: ...
    for k, v in u.items(): ...
    list(u.keys())
    list(u.values())

    Iterate keys directly or unpack pairs with .items().

    Pitfall: Looping for x in d yields only keys, not (key, value) pairs.

  • Comprehensions

    {x: x*x for x in range(4)}              # {0:0,1:1,2:4,3:9}
    {k: v for k, v in u.items() if v}        # filter

    Builds transformed or filtered dictionaries cleanly.

    Pitfall: Colliding keys overwrite earlier entries without error.

6. Tuples and sets

  • Tuples (immutable)

    t = (1, 2, 3)
    x, y, z = t          # unpacking
    t + (4, 5)           # (1,2,3,4,5)
    len(t)

    Immutable sequences suitable for fixed records and dictionary keys.

    Pitfall: A single-element tuple requires a trailing comma: (42,) is a tuple while (42) is an integer.

  • Sets (unique value collections)

    s = {1, 2, 3}
    s.add(4)
    s & {2, 3, 5}   # intersection: {2,3}
    s | {5}         # union
    set("abracadabra")  # {'a','b','r','c','d'}

    Unordered unique collections supporting set algebra and O(1) membership checks.

    Pitfall: {} creates an empty dict, NOT an empty set: always use set() for an empty set.

7. Control Flow

  • if / elif / else

    if x > 0:
        print("positive")
    elif x == 0:
        print("zero")
    else:
        print("negative")
    # Ternary
    label = "ok" if x > 0 else "ko"

    Multi-branch conditionals and inline conditional expressions.

    Pitfall: Be careful with truthiness on numbers: if x: rejects 0 just like None.

  • for / while

    for i in range(5):
        print(i)
    for item in my_list:
        ...
    for i, item in enumerate(my_list):
        ...
    while cond:
        ...

    Iterate ranges, sequences, or index+value pairs with enumerate().

    Pitfall: Avoid indexing via range(len(xs)): prefer iterating items directly or using enumerate(xs).

  • break / continue

    for n in nums:
        if n < 0:
            continue   # skip
        if n > 100:
            break      # exit
        ...

    Skips the remainder of the current pass or exits the innermost loop.

    Pitfall: A loop else: block only executes when the loop finishes naturally without hitting break.

  • try / except

    try:
        value = int(s)
    except ValueError as err:
        print("not a number:", err)
    else:
        print("ok:", value)
    finally:
        print("always")

    Structured exception handling separating error path, success (else), and cleanup (finally).

    Pitfall: Never use bare except: because it swallows KeyboardInterrupt and SystemExit.

8. Functions

  • Definition

    def add(a, b):
        return a + b
    
    # Optional types (type hints)
    def greet(name: str = "World") -> str:
        return f"Hello, {name}"

    Defines functions with optional defaults and type annotations.

    Pitfall: Never use a mutable default like items=[] in a def signature: use None and initialize inside.

  • Variable args

    def add_all(*numbers):
        return sum(numbers)
    add_all(1, 2, 3)        # 6
    add_all(*[1, 2, 3])     # 6
    
    def configure(**opts):
        print(opts)
    configure(host="localhost", port=8000)

    Captures variadic positional (*args) and keyword (**kwargs) arguments.

    Pitfall: Signature order is strict: positional -> *args -> keyword-only -> **kwargs.

  • lambda

    square = lambda x: x * x
    square(5)              # 25
    sorted(items, key=lambda i: i.price)

    Anonymous single-expression function; use def for anything multi-statement.

    Pitfall: Lambdas defined inside a loop bind the loop variable lazily unless pinned with x=x.

9. Classes

  • Base class

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def distance_origin(self):
            return (self.x ** 2 + self.y ** 2) ** 0.5
    
    p = Point(3, 4)
    p.distance_origin()  # 5.0

    Initializes instance attributes in __init__ and defines methods taking self.

    Pitfall: Mutable class-body attributes outside __init__ are shared across all instances.

  • Inheritance

    class Animal:
        def __init__(self, name):
            self.name = name
        def sound(self):
            return "..."
    
    class Dog(Animal):
        def sound(self):
            return "woof"
    
    Dog("Fido").sound()  # 'woof'

    Specializes parent behavior via subclassing and method overrides.

    Pitfall: Remember super().__init__(...) whenever a subclass defines its own __init__.

  • Dunder methods

    class Money:
        def __init__(self, n):
            self.n = n
        def __repr__(self):
            return f"Money({self.n})"
        def __add__(self, other):
            return Money(self.n + other.n)

    Customizes representation and arithmetic/comparison operators.

    Pitfall: Return NotImplemented rather than raising TypeError in rich comparison methods for unknown right operands.

10. Modules and import

  • Import

    import math
    from math import sqrt, pi
    from math import sqrt as sqroot
    import os.path as p

    Imports modules or selected symbols with optional aliases.

    Pitfall: Avoid wildcard imports (from m import *) as they shadow names silently.

  • Useful standard library

    import json, datetime, pathlib, re, collections, itertools, csv
    
    json.dumps({"a": 1})
    datetime.date.today()
    pathlib.Path("file.txt").read_text()
    re.findall(r"\d+", "I have 3 apples and 12 pears")
    collections.Counter("abracadabra")

    Built-in batteries for JSON, paths, dates, regex, and counting.

    Pitfall: Specify encoding="utf-8" explicitly when calling read_text() or open() across operating systems.

11. Modern Python

  • Type hints

    def total(nums: list[int]) -> int:
        return sum(nums)
    
    def find(item_id: int) -> str | None:
        ...
    
    from typing import Callable
    f: Callable[[int], int] = lambda x: x + 1

    Static annotations checked by mypy/pyright; Python does NOT enforce them at runtime.

    Pitfall: Do not assume annotations validate untrusted runtime arguments automatically.

  • dataclass

    from dataclasses import dataclass, field
    
    @dataclass
    class Point:
        x: float
        y: float
    
    @dataclass(frozen=True)
    class Coord:
        lat: float
        lon: float
    
    @dataclass
    class Basket:
        items: list = field(default_factory=list)

    Generates __init__, __repr__, and __eq__ cleanly for data-holding classes.

    Pitfall: Never use items: list = []: use field(default_factory=list) or Python raises ValueError.

  • Context manager

    with open("f.txt", encoding="utf-8") as f:
        data = f.read()
    
    from contextlib import contextmanager, suppress
    
    @contextmanager
    def timer():
        import time; t0 = time.perf_counter()
        try:
            yield
        finally:
            print(time.perf_counter() - t0)
    
    with suppress(FileNotFoundError):
        open("maybe.txt", encoding="utf-8").read()

    Guarantees deterministic cleanup even when exceptions occur inside the block.

    Pitfall: Without try/finally around yield in a @contextmanager, cleanup code is skipped on exceptions.

  • Decorators

    from functools import wraps, lru_cache
    
    def log(func):
        @wraps(func)
        def wrapper(*a, **kw):
            print(func.__name__)
            return func(*a, **kw)
        return wrapper
    
    @lru_cache(maxsize=None)
    def fib(n):
        return n if n < 2 else fib(n-1) + fib(n-2)

    Wraps functions cleanly to add logging, caching, or cross-cutting checks.

    Pitfall: Forgetting @wraps(func) erases the wrapped function’s __name__ and docstring.