Sponsored Reserved space — layout preview until AdSense is connected

Reference library

Python code samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

6 matches
Sponsored Reserved space — layout preview until AdSense is connected
Strings & text easy

F-string formatting

Embed variables and expressions inside readable f-strings.

strings f-string formatting
Python
name = "Ada"
score = 97.5
label = f"{name} scored {score:.1f}%"
print(label)
print(f"Next year: {2026 + 1}")
4 1 Open
Lists & loops medium

List comprehension filter

Build a new list in one line by filtering and transforming items.

lists comprehension filter
Python
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)
4 0 Open
Functions & basics easy

Function with default argument

Define a reusable greet helper with an optional prefix parameter.

functions defaults basics
Python
def greet(name, prefix="Hello"):
    return f"{prefix}, {name}!"


print(greet("Python"))
print(greet("World", prefix="Hi"))
3 0 Open
Functions & basics medium

Return multiple values

Return a tuple of results and unpack them at the call site.

functions return tuple
Python
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}")
4 0 Open
Files & data medium

Read a text file with pathlib

Open and read UTF-8 text using pathlib.Path — modern and portable.

files pathlib io
Python
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.")
2 0 Open
Errors & debugging medium

Raise a clear custom error

Validate input early and raise ValueError with a helpful message.

errors raise validation
Python
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)
3 1 Open

Browse by section

Each section groups closely related Python snippets.