Programming

Python Quick Reference Cheat Sheet

Everyday Python 3 cheat sheet: variables, f-strings, lists & slicing, copying, dictionaries, comprehensions, functions, CSV/JSON files, pytest, venv, and OOP.

1 min readUpdated 2026-11-30

Variables, f-Strings & Strings

python
name = "  alex smith  "
clean = name.strip().title()      # "Alex Smith"
price = 49.5
print(f"{clean} paid ${price:.2f}")

Lists, Slicing, Comprehensions & Safe Copies

python
skills = ["Python", "SQL", "Git"]
skills.append("Pytest")
first, last = skills[0], skills[-1]
top_two = skills[:2]
backup = skills.copy()            # Independent list copy!

upper_skills = [s.upper() for s in skills if len(s) > 2]

Dictionaries & Loops

python
user = {"name": "Maya", "track": "Backend"}
streak = user.get("streak", 0)

for key, val in user.items():
    print(f"{key}: {val}")

for idx, skill in enumerate(skills, start=1):
    print(idx, skill)

Functions, *args / **kwargs, Errors & Testing (pytest)

python
def add(a: int, b: int = 0) -> int:
    return a + b

try:
    num = int("42")
except ValueError as err:
    print("Invalid number:", err)

# pytest: test_math.py
import pytest

@pytest.mark.parametrize("a,b,expected", [(2, 3, 5), (0, 0, 0)])
def test_add(a, b, expected):
    assert add(a, b) == expected

Files (TXT, CSV & JSON) & Virtual Environments

python
import csv, json

with open("data.json", "w", encoding="utf-8") as f:
    json.dump({"ok": True}, f, indent=2)

with open("grades.csv", "r", encoding="utf-8", newline="") as f:
    rows = list(csv.DictReader(f))
bash
python3 -m venv .venv && source .venv/bin/activate
python -m pip install requests && pip freeze > requirements.txt

Classes & Inheritance (super())

python
class Account:
    def __init__(self, owner: str, balance: float = 0):
        self.owner = owner
        self.balance = balance

class Savings(Account):
    def __init__(self, owner: str, balance: float = 0, rate: float = 0.05):
        super().__init__(owner, balance)
        self.rate = rate