Print several values
Output & f-stringsprint() joins its arguments with a space.
print("Total:", 42, "items")
Total: 42 items
Every snippet here shows the output it genuinely produces — they are executed and checked, not written from memory. Filter by topic, search for what you need, copy it, or open it in the playground and change it.
92 snippets
print() joins its arguments with a space.
print("Total:", 42, "items")
Total: 42 items
An f-string drops values straight into the sentence.
name = "Ana"
print(f"Hello, {name}!")
Hello, Ana!
:.2f shows exactly two decimal places.
price = 12.3456
print(f"Price: {price:.2f}")
Price: 12.35
:, makes big numbers readable.
print(f"{1234567:,}")
1,234,567
<10 pads right, >10 pads left — how you line up columns.
for item, qty in [("apple", 3), ("banana", 12)]:
print(f"{item:<10}{qty:>4}")
apple 3
banana 12
:.1% turns 0.256 into 25.6%.
print(f"{0.256:.1%}")
25.6%
end= replaces the line break.
for i in range(3):
print(i, end=" ")
print()
0 1 2
The = suffix prints the name and the value.
total = 99
print(f"{total=}")
total=99
Useful for comparing user input.
print("Python".upper(), "Python".lower())
PYTHON python
Removes spaces and newlines from both ends.
print(repr(" hi ".strip()))
'hi'
Splits on the separator you give it.
print("a,b,c".split(","))
['a', 'b', 'c']
The separator goes in front of .join().
print(" & ".join(["eggs", "milk", "bread"]))
eggs & milk & bread
Returns a new string — the original is unchanged.
print("2026-01-05".replace("-", "/"))
2026/01/05
in, startswith and endswith all return True or False.
f = "report.csv"
print("port" in f, f.startswith("re"), f.endswith(".csv"))
True True True
[start:stop] — stop is not included.
s = "abcdefgh"
print(s[:3], s[3:5], s[-2:])
abc de gh
[::-1] steps backwards through it.
print("stressed"[::-1])
desserts
Handy for validating input.
print("123".isdigit(), "abc".isalpha(), "a1".isalnum())
True True True
Counts non-overlapping matches.
print("banana".count("an"))
2
/ gives a decimal, // throws away the remainder.
print(7 / 2, 7 // 2, 7 % 2)
3.5 3 1
** is 'to the power of'.
print(2 ** 10)
1024
round() to n decimals; watch banker's rounding on .5.
print(round(3.14159, 2), round(2.5), round(3.5))
3.14 2 4
Work on any numbers you pass.
print(abs(-7), min(3, 9, 1), max([3, 9, 1]))
7 1 9
sum() with an optional starting value.
print(sum([1, 2, 3, 4]))
10
int() truncates, it does not round.
print(int("42") + 1, float("3.5"), str(99) + "!")
43 3.5 99!
math has the rest of school maths.
import math
print(math.sqrt(144), math.ceil(4.1), math.floor(4.9))
12.0 5 4
statistics.mean beats writing it by hand.
import statistics
print(statistics.mean([2, 4, 4, 6]))
4
append adds one, extend adds many, pop removes and returns.
xs = [1, 2]
xs.append(3)
xs.extend([4, 5])
last = xs.pop()
print(xs, last)
[1, 2, 3, 4] 5
insert takes a position; remove takes a value.
xs = ["a", "c"]
xs.insert(1, "b")
xs.remove("a")
print(xs)
['b', 'c']
sort() changes the list; sorted() returns a new one.
xs = [3, 1, 2]
print(sorted(xs), sorted(xs, reverse=True), xs)
[1, 2, 3] [3, 2, 1] [3, 1, 2]
key= says what to sort on.
people = [("Ana", 30), ("Bo", 25)]
print(sorted(people, key=lambda p: p[1]))
[('Bo', 25), ('Ana', 30)]
index finds the first match.
xs = ["a", "b", "a"]
print(xs.index("b"), xs.count("a"), len(xs))
1 2 3
Same [start:stop:step] as strings.
xs = [0, 1, 2, 3, 4, 5]
print(xs[2:5], xs[::2], xs[::-1])
[2, 3, 4] [0, 2, 4] [5, 4, 3, 2, 1, 0]
enumerate gives you position and value together.
for i, item in enumerate(["a", "b"], start=1):
print(i, item)
1 a
2 b
zip stops at the shorter one.
for name, score in zip(["Ana", "Bo"], [9, 7]):
print(name, score)
Ana 9
Bo 7
A comprehension with two for clauses.
nested = [[1, 2], [3, 4]]
print([x for row in nested for x in row])
[1, 2, 3, 4]
dict.fromkeys preserves first-seen order.
xs = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(xs)))
[3, 1, 2]
get() returns a default instead of crashing.
user = {"name": "Ana"}
print(user.get("name"), user.get("age", "unknown"))
Ana unknown
Assign to add or overwrite.
d = {"a": 1}
d["b"] = 2
d.update({"a": 10})
del d["b"]
print(d)
{'a': 10}
items() gives key and value.
for k, v in {"a": 1, "b": 2}.items():
print(k, "->", v)
a -> 1
b -> 2
in checks keys, not values.
d = {"a": 1, "b": 2}
print(list(d.keys()), list(d.values()), "a" in d)
['a', 'b'] [1, 2] True
The classic tally pattern.
words = ["a", "b", "a"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
{'a': 2, 'b': 1}
Counter does the same in one line.
from collections import Counter
print(Counter("mississippi").most_common(2))
[('i', 4), ('s', 4)]
setdefault creates the list on first sight.
pairs = [("fruit", "apple"), ("veg", "leek"), ("fruit", "pear")]
g = {}
for k, v in pairs:
g.setdefault(k, []).append(v)
print(g)
{'fruit': ['apple', 'pear'], 'veg': ['leek']}
sorted() over .items() with a key.
scores = {"Ana": 9, "Bo": 7, "Cy": 8}
print(sorted(scores.items(), key=lambda kv: -kv[1]))
[('Ana', 9), ('Cy', 8), ('Bo', 7)]
zip then dict.
print(dict(zip(["a", "b"], [1, 2])))
{'a': 1, 'b': 2}
A set drops duplicates.
print(sorted(set([1, 2, 2, 3])))
[1, 2, 3]
In both, in either, in one only.
a, b = {1, 2, 3}, {2, 3, 4}
print(sorted(a & b), sorted(a | b), sorted(a - b))
[2, 3] [1, 2, 3, 4] [1]
in on a set is much faster than on a list.
allowed = {"admin", "editor"}
print("admin" in allowed)
True
Use them for values that should not change.
point = (3, 4)
x, y = point
print(x, y, len(point))
3 4 2
range(start, stop, step) — stop excluded.
print(list(range(5)), list(range(2, 10, 3)))
[0, 1, 2, 3, 4] [2, 5, 8]
The comprehension replaces append loops.
print([n * n for n in range(6)])
[0, 1, 4, 9, 16, 25]
Add an if at the end.
print([n for n in range(10) if n % 2 == 0])
[0, 2, 4, 6, 8]
Comprehensions work for dicts too.
prices = {"a": 10, "b": 20}
print({k: v * 1.2 for k, v in prices.items()})
{'a': 12.0, 'b': 24.0}
break leaves the loop, continue skips an item.
for n in range(10):
if n == 3:
continue
if n > 5:
break
print(n, end=" ")
print()
0 1 2 4 5
Ask a yes/no question about a whole list.
xs = [2, 4, 6]
print(all(n % 2 == 0 for n in xs), any(n > 5 for n in xs))
True True
Sort the keys as you go.
d = {"b": 2, "a": 1}
for k in sorted(d):
print(k, d[k])
a 1
b 2
Only the first matching branch runs.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("C")
B
Empty things and zero are falsy.
for v in [0, "", [], {}, None, "x"]:
print(repr(v), bool(v))
0 False
'' False
[] False
{} False
None False
'x' True
The conditional expression.
n = 7
print("even" if n % 2 == 0 else "odd")
odd
Reads like maths and works like it.
age = 25
print(18 <= age < 65)
True
or falls back when the left side is falsy.
name = ""
print(name or "anonymous")
anonymous
def, then the name, then the inputs.
def greet(name):
return f"Hello, {name}"
print(greet("Ana"))
Hello, Ana
Callers can leave them out.
def power(n, exp=2):
return n ** exp
print(power(5), power(2, 10))
25 1024
Really a tuple you can unpack.
def stats(xs):
return min(xs), max(xs)
lo, hi = stats([3, 9, 1])
print(lo, hi)
1 9
*args collects the extras.
def total(*nums):
return sum(nums)
print(total(1, 2, 3, 4))
10
**kwargs collects named extras.
def show(**opts):
return sorted(opts.items())
print(show(size=3, color="red"))
[('color', 'red'), ('size', 3)]
lambda, mostly used as a sort key.
words = ["pear", "fig", "banana"]
print(sorted(words, key=lambda w: len(w)))
['fig', 'pear', 'banana']
The docstring is what help() shows.
def area(w, h):
"""Return the area of a rectangle."""
return w * h
print(area(3, 4), area.__doc__)
12 Return the area of a rectangle.
try the risky thing, except the failure.
try:
n = int("abc")
except ValueError:
print("not a number")
not a number
as err gives you the detail.
try:
1 / 0
except ZeroDivisionError as err:
print("failed:", err)
failed: division by zero
finally runs whether or not it failed.
try:
print("working")
finally:
print("cleaned up")
working
cleaned up
Fail loudly with a useful message.
def withdraw(balance, amount):
if amount > balance:
raise ValueError("insufficient funds")
return balance - amount
try:
withdraw(10, 50)
except ValueError as e:
print(e)
insufficient funds
isinstance is the polite way to ask.
print(isinstance(3, int), isinstance("x", (int, str)))
True True
type and dir when you are lost.
print(type([]).__name__, [m for m in dir([]) if m == "append"])
list ['append']
with closes the file for you.
with open("notes.txt", "w") as f:
f.write("line one\nline two\n")
with open("notes.txt") as f:
print(f.read().strip())
line one
line two
Loop the file object directly.
with open("notes.txt", "w") as f:
f.write("a\nb\n")
with open("notes.txt") as f:
for line in f:
print(line.strip())
a
b
dumps writes, loads reads.
import json
s = json.dumps({"b": 2, "a": 1}, sort_keys=True)
print(s, json.loads(s)["a"])
{"a": 1, "b": 2} 1
indent makes it human-readable.
import json
print(json.dumps({"name": "Ana", "xp": 20}, indent=2))
{
"name": "Ana",
"xp": 20
}
DictReader gives you named columns.
import csv, io
rows = csv.DictReader(io.StringIO("name,xp\nAna,20\nBo,35"))
for r in rows:
print(r["name"], r["xp"])
Ana 20
Bo 35
date.today() and ISO formatting.
from datetime import date
d = date(2026, 3, 9)
print(d.isoformat(), d.year, d.strftime("%d %B %Y"))
2026-03-09 2026 09 March 2026
timedelta does date arithmetic.
from datetime import date, timedelta
print(date(2026, 1, 30) + timedelta(days=3))
2026-02-02
Subtracting gives a timedelta.
from datetime import date
print((date(2026, 3, 1) - date(2026, 1, 1)).days)
59
strptime parses with a format string.
from datetime import datetime
print(datetime.strptime("09/03/2026", "%d/%m/%Y").date())
2026-03-09
Seeding makes the result repeatable.
import random
random.seed(42)
print(random.randint(1, 100), random.choice("abcde"))
82 a
re for anything a simple search cannot do.
import re
print(re.findall(r"\d+", "order 66 shipped 2 items"))
['66', '2']
re.sub swaps every match.
import re
print(re.sub(r"\s+", " ", "too many spaces"))
too many spaces
fullmatch checks the whole string.
import re
print(bool(re.fullmatch(r"[\w.]+@[\w.]+", "a.b@example.com")))
True
pathlib beats gluing strings together.
from pathlib import Path
p = Path("reports") / "q1.csv"
print(p, p.suffix, p.stem)
reports/q1.csv .csv q1
defaultdict skips the setdefault dance.
from collections import defaultdict
g = defaultdict(list)
g["fruit"].append("pear")
print(dict(g))
{'fruit': ['pear']}
itertools for combinatorics.
from itertools import combinations
print(list(combinations("abc", 2)))
[('a', 'b'), ('a', 'c'), ('b', 'c')]
lru_cache remembers past answers.
from functools import lru_cache
@lru_cache
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(30))
832040
Readable records without a class.
from collections import namedtuple
P = namedtuple("P", "x y")
p = P(3, 4)
print(p.x, p.y, p)
3 4 P(x=3, y=4)
Nothing matches that. Try a shorter word — the snippets are searched by title, description and code.
No site teaches everything, and pretending otherwise wastes your time. These are the free resources worth knowing about, with an honest note on what each is actually for.
Paste code and step through it one line at a time, watching variables, lists and function calls change. The single best way to fix a wrong mental model of how a loop or a reference actually works.
Free Official Python tutorialThe canonical explanation, written by the people who build the language. Drier than a course, but it is right, and it stays right.
Free Standard library referenceWhat is already installed, before you go looking for a package. Worth skimming the contents page once so you know what exists.
Exercises solved in your own editor against a real test suite, with volunteer mentors who review your solution and suggest a more idiomatic one.
Free Advent of CodeA December puzzle calendar, but every past year stays open. The early days of each year are approachable once you are comfortable with loops and dictionaries.
Free to audit CS50P — HarvardA full university introduction to programming with Python, lectures and problem sets included. Slower and more rigorous than a lesson here.
A complete book, free to read online, on pointing Python at tedious real work — files, spreadsheets, email, the web. The natural next step after the projects here.
Free PEP 8 — the style guideHow Python code is conventionally written and spaced. Read it once you can write code that works; it is about being readable to other people.
Partly free Real PythonLong, careful articles on specific topics — decorators, virtual environments, async. Many are free to read; some tutorials and the video courses are paid, so check before you commit time.
Free PyPIThe index of installable packages. Once you leave the browser and run Python locally, this is where the rest of the ecosystem lives.
Start free. No install, no card, no passive video marathon.