Reference library
Python code samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Strings & text
Format, split, join, and clean Python strings — the bread and butter of everyday scripts.
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}")
Split and join words
Turn a sentence into tokens, then rebuild it with a custom separator.
raw = "python split join example"
words = raw.split()
print(words)
joined = "-".join(words)
print(joined)
csv_line = "red,green,blue"
colors = csv_line.split(",")
print(" | ".join(colors))
Strip and normalize text
Remove stray whitespace and compare user input reliably.
messy = " Hello, Python! \n"
clean = messy.strip()
print(repr(clean))
user = " YES "
if user.strip().lower() == "yes":
print("Confirmed")
Lists & loops
Iterate, transform, and combine sequences with readable Python patterns.
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)
Enumerate with index
Loop with both index and value — cleaner than manual counters.
tasks = ["read docs", "write code", "run tests"]
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
Zip two lists
Pair items from parallel lists and iterate them together.
names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 100]
for name, score in zip(names, scores):
print(f"{name}: {score}")
print(list(zip(names, scores)))
Functions & basics
Small reusable building blocks — parameters, returns, and clear function design.
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}")
Files & data
Read files safely and parse common data formats without extra dependencies.
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.")
Parse JSON safely
Load JSON from a string and handle decode errors without crashing.
import json
payload = '{"name": "Ada", "skills": ["Python", "math"]}'
try:
data = json.loads(payload)
print(data["name"])
print(", ".join(data["skills"]))
except json.JSONDecodeError as exc:
print(f"Invalid JSON: {exc}")
Errors & debugging
Handle failures gracefully and write clearer error messages for future you.
Try/except ValueError
Convert user input to int inside try/except and show a friendly message.
raw = "42"
try:
value = int(raw)
print(f"Parsed: {value}")
except ValueError:
print(f"Could not parse {raw!r} as an integer.")
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)