Reference library
Python code samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
F-string formatting
Embed variables and expressions inside readable f-strings.
name = "Ada"
score = 97.5
label = f"{name} scored {score:.1f}%"
print(label)
print(f"Next year: {2026 + 1}")
List comprehension filter
Build a new list in one line by filtering and transforming items.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
doubled_evens = [n * 2 for n in numbers if n % 2 == 0]
print(doubled_evens)
names = ["ada", "linus", "guido"]
title_case = [name.title() for name in names if name]
print(title_case)
Function with default argument
Define a reusable greet helper with an optional prefix parameter.
def greet(name, prefix="Hello"):
return f"{prefix}, {name}!"
print(greet("Python"))
print(greet("World", prefix="Hi"))
Return multiple values
Return a tuple of results and unpack them at the call site.
def min_max(values):
if not values:
return None, None
return min(values), max(values)
data = [3, 9, 1, 7]
lo, hi = min_max(data)
print(f"range: {lo} .. {hi}")
Read a text file with pathlib
Open and read UTF-8 text using pathlib.Path — modern and portable.
from pathlib import Path
path = Path("notes.txt")
if path.is_file():
text = path.read_text(encoding="utf-8")
print(text[:200])
else:
print("File not found — create notes.txt to try this sample.")
Raise a clear custom error
Validate input early and raise ValueError with a helpful message.
def positive_only(n):
"""Return n if it is strictly positive."""
if n <= 0:
raise ValueError(f"Expected a positive number, got {n}")
return n
print(positive_only(5))
try:
positive_only(-1)
except ValueError as exc:
print(exc)
Browse by section
Each section groups closely related Python snippets.