Skip to main content
eLearner.app

Python Course

Cheatsheet

A quick reference — the essential syntax of modern Python on a single page. Press Ctrl/Cmd + P to print it.

Python · Cheatsheet — eLearner.app

Variables and types

  • Assignment

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

    No let/const/var: Python has no variable declaration, only assignment.

  • Types and conversions

    type(42)         # <class 'int'>
    int("42")        # 42
    str(3.14)        # '3.14'
    float("1.5")     # 1.5
    bool(0)          # False
  • 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

    Use == for equality, is only for None/True/False.

Strings

  • f-string

    name = "World"
    msg = f"Hello, {name}!"
    # Expressions and formatting:
    f"pi = {3.14159:.2f}"   # 'pi = 3.14'
    f"{42:>5}"              # '   42'
  • 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")
  • Slicing

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

Numbers and math

  • Operators

    7 // 2     # 3   (integer division)
    7 % 2      # 1   (remainder)
    2 ** 10    # 1024 (exponentiation)
    abs(-5)    # 5
    round(1.6) # 2
  • 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

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
  • 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
  • Sorting

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

Dictionaries

  • Create and access

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

    for k in u: ...
    for k, v in u.items(): ...
    list(u.keys())
    list(u.values())
  • 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

Tuples and sets

  • Tuples (immutable)

    t = (1, 2, 3)
    x, y, z = t          # unpacking
    t + (4, 5)           # (1,2,3,4,5)
    len(t)
  • 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'}

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"
  • for / while

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

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

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

Functions

  • Definition

    def add(a, b):
        return a + b
    
    # Optional types (type hints)
    def greet(name: str = "World") -> str:
        return f"Hello, {name}"
  • 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)
  • lambda

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

    Lambda = anonymous function with a single expression. Use def for longer blocks.

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
  • 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'
  • 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)

Modules and import

  • Import

    import math
    from math import sqrt, pi
    from math import sqrt as sqroot
    import os.path as p
  • 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")

Modern Python

  • Type hints

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

    Annotations only: Python does NOT enforce them at runtime. Use mypy for static checking.

  • 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)

    Never default = []: use field(default_factory=list).

  • Context manager

    with open("f.txt") 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").read()
  • 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)
eLearner.app · Python Course · cheatsheet generated from lesson content.