Python Syntax Quick Reference: The Patterns Every Developer Uses Daily
A concise Python syntax quick reference covering variables, loops, functions, classes, list comprehensions, error handling, and more — with runnable examples in your browser.
Python is famous for being readable, but readable does not mean obviously memorable. Even experienced developers look things up constantly — list comprehension syntax, how to unpack a nested dict, whether to use @property or a plain method, the exact signature of sorted(). This quick reference covers the patterns that come up most in everyday Python code.
Every example here is runnable in your browser via our Interactive Python Cheat Sheet — no install needed, just click Run.
Variables and Types
Python is dynamically typed. Variables hold references to objects, not typed memory slots. Type annotations are optional and do not change runtime behaviour — they exist for tooling and readability.
name = "Alice" # str
age = 30 # int
score = 98.5 # float
active = True # bool
nothing = None # NoneType
Runtime type inspection
print(type(name)) # <class 'str'>
isinstance(age, int) # True
Type hint (optional, for tooling)
greeting: str = "Hello"
f-strings are the preferred string formatting method since Python 3.6:
greeting = f"Hello, {name}! You are {age} years old."
result = f"Score: {score:.1f}%" # "Score: 98.5%"
debug = f"{name=}, {age=}" # "name='Alice', age=30"
Collections
# List — ordered, mutable, allows duplicates
fruits = ["apple", "banana", "cherry"]
fruits.append("mango") # add to end
fruits.insert(1, "blueberry") # insert at index
fruits.pop() # remove and return last item
fruits.remove("banana") # remove first occurrence by value
fruits[1:3] # slice: ["blueberry", "cherry"]
Tuple — ordered, immutable
coords = (40.7128, -74.0060)
lat, lng = coords # unpack
Dict — key-value, insertion-ordered since Python 3.7
user = {"name": "Alice", "age": 30}
user["email"] = "alice@example.com" # add or update key
user.get("phone", "N/A") # safe get with default
user.pop("age") # remove key, returns value
list(user.keys()) # ["name", "email"]
list(user.items()) # [("name", "Alice"), ("email", "...")]
Set — unordered, unique values
tags = {"python", "web", "python"} # {"python", "web"}
tags.add("backend")
tags.discard("web") # removes if present, no error if absent
Control Flow
# Ternary (conditional expression)
label = "adult" if age >= 18 else "minor"
Walrus operator := (Python 3.8+) — assign and test in one step
import re
if m := re.search(r"\d+", "order 42"):
print(m.group()) # "42"
Pattern matching (Python 3.10+)
match command:
case "quit":
exit()
case "help" | "?":
show_help()
case _:
print(f"Unknown command: {command}")
List Comprehensions
This is the pattern that impresses everyone once mastered — and the one most beginners underuse:
# [expression for item in iterable if condition]
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
upper = [s.upper() for s in ["a", "b", "c"]]
Nested — generates (x, y) pairs
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
Dict comprehension
lengths = {word: len(word) for word in ["cat", "elephant", "ox"]}
Set comprehension
unique_lengths = {len(word) for word in ["cat", "elephant", "ox"]}
Generator expression — same syntax, round brackets, lazy evaluation
big_sum = sum(x**2 for x in range(1_000_000)) # barely uses memory
Functions
def greet(name, greeting="Hello"):
"""Returns a greeting string."""
return f"{greeting}, {name}!"
*args collects extra positional args as a tuple
**kwargs collects extra keyword args as a dict
def log(level, args, *kwargs):
print(f"[{level}]", *args, kwargs)
Keyword-only arguments (after *)
def connect(host, *, port=5432, timeout=30):
...
Lambda — anonymous one-liner functions
double = lambda x: x * 2
sorted_users = sorted(users, key=lambda u: u["age"])
Type hints for function signatures
def add(a: int, b: int) -> int:
return a + b
Classes
class Animal:
species_count = 0 # class variable, shared across instances
def __init__(self, name: str, species: str): self.name = name # instance variable self.species = species Animal.species_count += 1
def speak(self) -> str: return f"{self.name} makes a sound"
def __repr__(self) -> str: # developer-facing string representation return f"Animal({self.name!r}, {self.species!r})"
def __str__(self) -> str: # user-facing string representation return self.name
class Dog(Animal): def speak(self) -> str: # override parent method return f"{self.name} says: Woof!"
dog = Dog("Rex", "Canis lupus") print(dog.speak()) # Rex says: Woof! print(isinstance(dog, Animal)) # True
Dataclasses (Python 3.7+) auto-generate __init__, __repr__, and __eq__:
from dataclasses import dataclass, field
@dataclass class Point: x: float y: float label: str = ""
def distance(self) -> float: return (self.x2 + self.y2) ** 0.5
p = Point(3.0, 4.0, "origin") print(p.distance()) # 5.0
Error Handling
try:
result = int("not a number")
except ValueError as e:
print(f"Conversion failed: {e}")
except (TypeError, OverflowError) as e:
print(f"Type or overflow error: {e}")
else:
print("Success — this runs only if no exception was raised")
finally:
print("Always runs — use for cleanup (close files, release locks)")
Raising exceptions
def divide(a, b):
if b == 0:
raise ValueError("Denominator cannot be zero")
return a / b
Custom exception class
class AppError(Exception):
def __init__(self, message, code=None):
super().__init__(message)
self.code = code
Working with Files
# Read entire file
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
Read line by line — memory-efficient for large files
with open("data.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
Write
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, file!")
JSON
import json
with open("config.json") as f:
config = json.load(f)
with open("config.json", "w") as f: json.dump(config, f, indent=2)
Always use with — it guarantees the file is closed even if an exception occurs.
Generators and Itertools
# Generator function — yields values lazily, one at a time
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fibonacci() first_ten = [next(gen) for _ in range(10)] # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Generator expression — like a lazy list comprehension
big_squares = (x**2 for x in range(1_000_000)) # uses almost no memory
import itertools
Chain multiple iterables into one
all_items = list(itertools.chain([1, 2], [3, 4], [5, 6]))
Group consecutive equal-key items
from itertools import groupby
data = sorted([("a", 1), ("b", 3), ("a", 2)], key=lambda x: x[0])
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
Sliding windows of size n
from itertools import islice
def sliding_window(iterable, n):
it = iter(iterable)
window = tuple(islice(it, n))
if len(window) == n:
yield window
for item in it:
window = window[1:] + (item,)
yield window
Common Gotchas — and the Pythonic Fix
Mutable default arguments — one of the most common Python bugs:
# Bug: the list is created once and shared across all calls
def append_to(item, target=[]):
target.append(item)
return target
Fix: use None as the sentinel
def append_to(item, target=None):
if target is None:
target = []
target.append(item)
return target
Catching broad exceptions silently:
# Bad — hides real errors
try:
risky_operation()
except Exception:
pass
Better — log at minimum; only catch what you can handle
import logging
try:
risky_operation()
except SpecificError as e:
logging.warning("risky_operation failed: %s", e)
The Full Interactive Reference
This covers the most-used daily patterns, but Python has a lot more ground — decorators, context managers, async/await, metaclasses, NumPy, Pandas, type hints deep-dive, and 20+ more topics.
For the complete reference with runnable code for every example, open our Interactive Python Cheat Sheet. Every snippet is editable and executable in-browser via Pyodide. Press / or Cmd+K to jump to any topic instantly.
Read next: How to Run Python in Your Browser Without Installing Anything — the technology behind in-browser Python execution and when to use it.