Sponsored Reserved space — layout preview until AdSense is connected

Reference library

Python code samples

Easy snippets you can copy, study, and run in the browser editor.

7 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
Strings & text easy

Split and join words

Turn a sentence into tokens, then rebuild it with a custom separator.

strings split join
Python
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))
5 0 Open
Strings & text easy

Strip and normalize text

Remove stray whitespace and compare user input reliably.

strings strip input
Python
messy = "  Hello, Python!  \n"
clean = messy.strip()
print(repr(clean))

user = "  YES  "
if user.strip().lower() == "yes":
    print("Confirmed")
2 0 Open
Lists & loops easy

Enumerate with index

Loop with both index and value — cleaner than manual counters.

loops enumerate lists
Python
tasks = ["read docs", "write code", "run tests"]

for i, task in enumerate(tasks, start=1):
    print(f"{i}. {task}")
5 0 Open
Lists & loops easy

Zip two lists

Pair items from parallel lists and iterate them together.

lists zip loops
Python
names = ["Ada", "Grace", "Katherine"]
scores = [98, 95, 100]

for name, score in zip(names, scores):
    print(f"{name}: {score}")

print(list(zip(names, scores)))
3 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
Errors & debugging easy

Try/except ValueError

Convert user input to int inside try/except and show a friendly message.

errors try-except input
Python
raw = "42"

try:
    value = int(raw)
    print(f"Parsed: {value}")
except ValueError:
    print(f"Could not parse {raw!r} as an integer.")
3 0 Open

Browse by section

Each section groups closely related Python snippets.