Python Cheat Sheet — Syntax and Patterns Reference
Modern Python syntax — functions, comprehensions, async/await, dataclasses — with copy-paste examples
Basic Variables, print, type
name = "Alice" # str
age = 30 # int
price = 19.99 # float
active = True # bool
nothing = None # NoneTypeprint(f"Hello {name}") # f-string (3.6+)
print("Score:", score) # multiple argstype(value) # returns type objectdef greet(name: str) -> None:Basic Collections: list, dict, set, tuple
# List — mutable, ordered
nums = [1, 2, 3]
nums.append(4)
nums[0] = 99# Tuple — immutable, ordered
point = (10, 20)
x, y = point # unpacking# Dict — key-value map
user = {"id": 1, "name": "Alice"}
user["email"] = "alice@example.com"
user.get("phone", "N/A") # safe get# Set — unique, unordered
tags = {"python", "fastapi", "pydantic"}
tags.add("async")list and dict are mutable. tuple and frozenset are immutable. Use collections.defaultdict for auto-initializing dicts.Truthiness & Boolean Context
False, None, 0, 0.0, "", [], {}, (), set()if mylist: # checks len()>0if mydict: # checks len()>0if x is None: # explicit None checkif not items: # empty check
Control if / elif / else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"# Ternary
status = "active" if user.active else "inactive"Loops
for i in range(5): # 0..4for i in range(1, 6): # 1..5for i in range(0, 10, 2): # step 2
for item in items:
print(item)for i, item in enumerate(items):
print(i, item)
while running:
...
if stop: break
continue # skip to next
Func def — define function
def greet(name):
return f"Hello {name}"def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b# *args, **kwargs
def log(msg, *args, **kwargs):
print(msg, args, kwargs)log("Error", 404, exc="timeout")
# ? Error (404,) {'exc': 'timeout'}*args collects positional extras as tuple. **kwargs collects keyword extras as dict. Positional-only (before /) and keyword-only (after *) params available in 3.8+.Func lambda — anonymous function
square = lambda x: x * x
result = square(5) # 25# Used with map/filter/sorted
nums = [1, 2, 3]
doubled = list(map(lambda x: x*2, nums))# key functions
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
pairs.sort(key=lambda p: p[1]) # sort by stringdef. Python's lambda is limited to single expression (no statements).Default Args & Closures
def greet(name="World"):
return f"Hello {name}"Keyword args order
def f(pos, /, standard, *, kw_only): ...# pos: positional-only, kw_only: keyword-only
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
Comp List comprehension
squares = [x**2 for x in range(10)]# with condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]# if-else inside
labels = ["even" if x%2==0 else "odd" for x in nums]for loop instead.Dict & Set Comprehensions
square_map = {x: x**2 for x in range(5)}# {0:0, 1:1, 2:4, 3:9, 4:16}
unique_squares = {x**2 for x in [1, -2, 3, -2, 1]}# {1, 4, 9}
gen = (x**2 for x in range(1000000))
# values computed on demand
Adv with — context manager (file I/O)
# File auto-close
with open("data.txt", "r") as f:
content = f.read() # file closes automatically# Multiple context managers
with open("in.txt") as fin, open("out.txt", "w") as fout:
fout.write(fin.read())with guarantees cleanup even on exception. Custom context managers implement __enter__ / __exit__ or use @contextmanager decorator from contextlib.Adv @dataclass — boilerplate-free classes
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
# auto __init__, __repr__, __eq__from dataclasses import dataclass, field
@dataclass
class User:
id: int
name: str
tags: list[str] = field(default_factory=list)@dataclass auto-generates __init__, __repr__, __eq__. field(default_factory=list) avoids mutable default pitfall. Python 3.10+ supports list[str] syntax for type hints.Custom Decorator
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.2f}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)
@functools.wraps(func) to preserve __name__, __doc__ of decorated function. Decorators are just callables that wrap functions.Async async def / await — concurrency
import asyncio
async def fetch_data():
await asyncio.sleep(1) # non-blocking sleep
return {"result": 42}
async def main():
data = await fetch_data()
print(data)
asyncio.run(main())async def defines coroutine function. await pauses until coroutine completes. Run with asyncio.run() (main) or await inside another async function. Use FastAPI or Starlette for web apps.Concurrent Execution
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))# all run concurrently, return list of results
task = asyncio.create_task(background_job())
# don't await immediately
gather() waits for all. create_task() schedules and returns Task immediately. Cancel tasks on shutdown if needed.Ctrl try / except / finally
try:
result = 10 / divisor
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("Success!", result)
finally:
cleanup() # always runselse runs if no exception. finally runs always (cleanup). Catch specific exceptions first, broad ones last.Raise Exceptions
raise ValueError("Invalid input")
raise TypeError("Expected str")
class AppError(Exception):
pass
raise AppError("Something went wrong")
Modern := walrus — assignment expression
# Assign inside expression
if (n := len(items)) > 0:
print(f"List has {n} items")# While reading lines from file
while (line := f.readline()):
process(line):= assigns and returns value. Reduces duplicate calls. Use sparingly — readability matters. Not for complex expressions.Modern match — pattern matching (3.10+)
match command:
case ["goto", x, y]:
print(f"Go to {x},{y}")
case ["quit"]:
print("Goodbye")
case _:
print("Unknown")match status:
case 200:
print("OK")
case 404:
print("Not found")
case int(code) if code >= 500:
print("Server error")match is like switch but powerful — matches on structure, type, and value. Guard clauses (if after case) add conditions.Modern Positional-only & keyword-only args (3.8+)
def greet(name, /, greeting="Hello", *, excited=False):
msg = f"{greeting} {name}"
if excited: msg += "!"
return msg
greet("Bob") # OK
greet(name="Bob") # ? name is positional-only
greet("Bob", "Hi", excited=True) # OK/ marks preceding args positional-only. * marks following args keyword-only. Signals API intent and prevents accidental misuse.Python syntax reference — the patterns you write every day
This covers the Python 3 syntax and patterns that come up constantly in real code. Not a tutorial — a reference for when you know what you want to do but need the exact syntax.
Data types and structures
nums = [1, 2, 3]— list (mutable, ordered)coords = (1, 2)— tuple (immutable)unique = {1, 2, 3}— set (no duplicates, unordered)person = {"name": "Alice", "age": 30}— dictx: int = 5— type annotation (Python 3.5+)
Comprehensions
[x * 2 for x in nums]— list comprehension[x for x in nums if x > 1]— with filter{k: v for k, v in d.items()}— dict comprehension{x for x in nums}— set comprehension(x for x in nums)— generator expression (lazy, memory-efficient)
Functions and decorators
def fn(a, b=10, *args, **kwargs):— positional, default, variadiclambda x: x * 2— anonymous function@property— getter without calling as method@staticmethod— method that doesn't receive self@classmethod— receives class as first arg, not instance@functools.lru_cache(maxsize=128)— memoize function results
Error handling
try: ... except ValueError as e: ...— catch specific exceptionexcept (TypeError, KeyError):— catch multiple typesfinally: ...— always runs, even on exceptionraise ValueError("message")— raise an exceptionraise ValueError("msg") from original_e— chain exceptions
Async / await
async def fetch(url): ...— define async functionresult = await some_coroutine()— await a coroutineasyncio.run(main())— entry point to run async codeawait asyncio.gather(task1, task2)— run multiple coroutines concurrently
Complete Developer Toolkit
Python is widely used for data processing, API backends, scripting, and automation. When your Python scripts process JSON data — from APIs, config files, or data pipelines — our JSON formatter validates the structure before you parse it in Python. Python's re module uses a similar regex syntax to JavaScript, so our regex tester is useful for testing and building patterns before adding them to your Python code. For database-backed Python apps, our SQL formatter cleans up the queries your Python ORMs or raw cursor.execute() calls run.
Python's uuid module generates the same UUIDs as our UUID generator — useful when testing UUID generation or creating test fixtures. The base64 module maps directly to our Base64 encoder, and Python's urllib.parse.quote() is the equivalent of our URL encoder. When debugging Python web APIs, our API response simulator mocks the JSON responses your Python clients consume. Our diff checker compares two Python script versions during code review. The Linux terminal cheat sheet covers the shell commands used to run, schedule, and manage Python scripts on servers.