Skip to main content

← All cheatsheets · Track →

🐍Updated 2026-05

Python basics cheatsheet — print, variables, lists, loops, functions

Patterns from the Foundations track, condensed into one page. Skim, copy, adapt. Pair with the linked lessons when you want the full "why".

Variables, types, strings

Print

Most common Python statement.

print("Hello, World!")

f-string

Inline expression in a string. The default since 3.6.

name = "Ada"
age = 36
print(f"{name} is {age}")

Type check

Find out what something is.

isinstance(x, (int, float))

Cast

Convert between types — always explicit.

n = int("42")
s = str(3.14)

Multiline string

Triple-quoted; preserves line breaks.

doc = """
Line 1
Line 2
"""

String split / join

Tokenise text and put it back.

"a,b,c".split(",")  # → ["a","b","c"]
",".join(["a","b","c"])

Conditionals & truthiness

if / elif / else

Branch on a condition. No switch in Python.

if x > 0:
    ...
elif x == 0:
    ...
else:
    ...

Truthy / falsy

Empty, 0, None, "" are falsy. Everything else is truthy.

if data:
    process(data)

Ternary

One-line if/else for assignment.

sign = "+" if x >= 0 else "-"

Lists, tuples, sets, dicts

List

Ordered, mutable, indexable.

xs = [1, 2, 3]
xs.append(4)

Tuple

Like list, but immutable. Good for fixed records.

point = (3, 4)

Set

Unique values, O(1) membership.

unique = set(xs)
3 in unique

Dict

Hash map from keys to values. Order-preserving since 3.7.

user = {"name": "Ada", "age": 36}

Slice

Substring/sublist with `[start:stop:step]`.

first3 = xs[:3]
reverse = xs[::-1]

List comp

Filtered / mapped list in one line.

evens = [x for x in xs if x % 2 == 0]

Dict comp

Build a dict in one expression.

squared = {x: x*x for x in range(5)}

Loops

for over list

Default loop.

for x in xs:
    process(x)

enumerate

Loop with an index counter.

for i, x in enumerate(xs, start=1):
    print(i, x)

zip

Walk two iterables in parallel.

for name, age in zip(names, ages):
    ...

while

Loop until a condition flips. Less common.

while not done:
    step()

break / continue

Exit / skip an iteration.

for x in xs:
    if x < 0:
        continue
    if x > 100:
        break

Functions

def

Define a function.

def greet(name: str) -> str:
    return f"Hello, {name}"

Defaults

Fallback values for parameters.

def repeat(x, n=2):
    return x * n

*args / **kwargs

Capture variable positional + keyword args.

def f(*args, **kwargs):
    ...

Lambda

Anonymous one-liner. Use for short callbacks.

add = lambda a, b: a + b

Errors & files

try / except

Handle exceptions; be specific.

try:
    n = int(s)
except ValueError:
    n = 0

raise

Throw a specific exception.

raise ValueError("must be positive")

with open

Read/write a file with auto-cleanup.

with open("data.txt") as f:
    text = f.read()

Want to actually learn these patterns, not just paste them? Open the Python basics cheatsheet track — each snippet has a full lesson behind it.