Cheat sheets / Python basics cheat sheet

Python basics cheat sheet

The core of Python on one page: values and variables, text, the four built-in collections, if/elif/else, for and while loops, functions, files and error handling. Print it or save it as a PDF.

Values and variables

name = "Asha"; age = 30; price = 9.99; ok = True
str, int, float, bool
x, y = 3, 4 x, y = y, x
multiple assignment, swap
type(age) # <class 'int'>
check a type
int("42"), float("2.5"), str(7)
convert between types
7 / 2, 7 // 2, 7 % 2, 2 ** 10
3.5, 3, 1, 1024

Strings

f"{name} is {age}"
f-string
f"{price:,.2f}" # 1,234.50
format numbers
s[0], s[-1], s[1:4], s[::-1]
index, slice, reverse
s.strip().lower().replace("a", "b")
clean and change
s.split(","), ", ".join(parts)
split and join
"py" in s, s.startswith("Py")
search

Lists, tuples, sets

items = [3, 1, 2] items.append(4); items.insert(0, 0)
add
items.remove(1); last = items.pop()
remove
sorted(items), items.sort(reverse=True)
new sorted list / sort in place
len(items), sum(items), max(items)
size and totals
point = (3, 4); x, y = point
tuple and unpacking
a | b, a & b, a - b
set union, intersection, difference

Dictionaries

user = {"name": "Ana", "age": 31}
create
user["name"], user.get("email", "-")
read; safe read with default
user["city"] = "Ghent"; user.pop("age")
add/change, remove
for key, value in user.items(): ...
loop over pairs
{w: len(w) for w in words}
dict comprehension

Conditions and loops

if x > 0: ... elif x == 0: ... else: ...
if / elif / else
label = "big" if n > 9 else "small"
one-line conditional
for i, item in enumerate(items, start=1): ...
position and item
for a, b in zip(names, scores): ...
two lists together
while balance < goal: ...
repeat while true; break / continue
[x * 2 for x in nums if x > 0]
list comprehension

Functions, files and errors

def area(w: float, h: float = 1) -> float: return w * h
function with type hints and default
def total(*nums): ... def opts(**kw): ...
any number of arguments
with open("a.txt", encoding="utf-8") as f: text = f.read()
read a file
Path("a.txt").write_text("hi", encoding="utf-8")
pathlib (from pathlib import Path)
try: n = int(s) except ValueError: n = 0
handle an error
raise ValueError("bad input")
report an error

PythonMates · pythonmates.com/cheat-sheets/python-basics/ · Python 3.15 · updated 2026-11-19

Learn it properly