Bookmark this page
Press Ctrl+D (Windows) or Cmd+D (Mac) to bookmark this page.
🐍 Python

Python Cheat Sheet

A practical Python cheat sheet for syntax, data structures, files, exceptions, and everyday workflows.

Syntax basicsData structuresFunctions and classesFiles, pip and venv

Basics and output

print("Hello, world!")
name = "Alex"
age = 27
is_admin = True

if age >= 18:
    print("Adult")
else:
    print("Minor")

Data types

name = "Alex"      # str
age = 27           # int
price = 12.5       # float
active = True      # bool
nothing = None     # NoneType

Lists, tuples, sets and dicts

items = ["a", "b", "c"]
items.append("d")
first = items[0]

coords = (10, 20)
unique = {1, 2, 2, 3}

user = {"name": "Alex", "role": "admin"}
role = user.get("role", "guest")
user["active"] = True

Loops and comprehensions

for item in items:
    print(item)

for index, item in enumerate(items, start=1):
    print(index, item)

squares = [n * n for n in range(5)]
evens = [n for n in range(10) if n % 2 == 0]

Functions and imports

def greet(name, title="Mr/Ms"):
    return f"Hi, {title} {name}!"

from pathlib import Path
from datetime import datetime

print(Path("notes.txt").exists())
print(datetime.now())

Exceptions

try:
    value = int(user_input)
except ValueError:
    value = 0
finally:
    print("Done")

assert value >= 0, "Value must be non-negative"
raise ValueError("Invalid input")

Classes and dataclasses

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hi, I'm {self.name}"

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

Files and JSON

with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()

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

with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)

Venv and pip

python -m venv .venv
source .venv/bin/activate   # macOS/Linux
.venv\Scripts\activate     # Windows

python -m pip install --upgrade pip
pip install requests
pip freeze > requirements.txt

Run and debug

python app.py
python -m http.server 8000
python -m pip list
python -m pip show requests
✓ Copied!