Python Basics Cheat Sheet

The everyday Python set: numbers, strings, lists, dicts, comprehensions, functions, files, exceptions, and datetime. Every example on this page was run and checked against Python 3.12.

Basics

# a comment: anything after # is ignored
name = "Ada"               # a variable — no declaration needed
age = 36                   # int
pi = 3.14159               # float
is_ok = True               # bool: True / False (capital T and F)
nothing = None             # None means "no value"
print("Hello,", name)      # Hello, Ada
print(type(age))           # <class 'int'>
name = input("Your name? ")  # input() always returns a string
age = int(input("Age? "))    # convert it: int() / float() / str()

Numbers & operators

7 / 2        # 3.5 — / is always float division
7 // 2       # 3 — floor division (rounds down)
7 % 2        # 1 — remainder
2 ** 10      # 1024 — power
divmod(17, 5)   # (3, 2) — quotient and remainder together
abs(-3)      # 3
round(3.14159, 2)   # 3.14
10_000       # 10000 — underscores make big numbers readable
int("42")    # 42     float("3.5")  # 3.5
int(3.9)     # 3 — int() truncates, it does not round
bool("")     # False  bool("x")  # True — empty values are falsy

Strings

s = "  Hello, World!  "
s.strip()              # 'Hello, World!' — trim both ends
"Hello".lower()        # 'hello'    "Hello".upper()  # 'HELLO'
"a-b-c".replace("-", "_")   # 'a_b_c'
"a,b,c".split(",")     # ['a', 'b', 'c']
", ".join(["a", "b"])  # 'a, b'
"hello".startswith("he")   # True — also: endswith()
"ell" in "hello"       # True — substring test
len("hello")           # 5
"hello"[1]             # 'e' — indexing starts at 0
"hello"[1:3]           # 'el' — slice: start inclusive, end exclusive
"hello"[-1]            # 'o' — negative index counts from the end
"banana".count("a")    # 3
"hello".find("l")      # 2 — first position, -1 if not found

f-strings & formatting

name, age = "Ada", 36
f"{name} is {age}"        # 'Ada is 36'
f"{3.14159:.2f}"          # '3.14' — 2 decimal places
f"{7:03d}"                # '007' — pad with zeros to width 3
f"{1234567:,}"            # '1,234,567' — thousands separator
f"{0.256:.1%}"            # '25.6%' — percentage
f"{name!r}"               # "'Ada'" — !r uses repr()
f"{age:>5}"               # '   36' — right-align in width 5
f"{name:<8}|"             # 'Ada     |' — left-align in width 8

Lists

nums = [3, 1, 4, 1, 5]
len(nums)                # 5
sum(nums)                # 14
max(nums), min(nums)     # (5, 1)
nums[1:3]                # [1, 4] — slice
nums[-1]                 # 5 — last element
nums.count(1)            # 2
nums.index(4)            # 2 — first position
sorted(nums)             # [1, 1, 3, 4, 5] — sorted() returns a new list
nums.sort()              # sorts in place, returns None
nums.append(6)           # add to the end
nums.insert(0, 0)        # insert at a position
nums.remove(1)           # remove the first 1
nums.pop()               # remove and return the last item
nums.reverse()           # reverse in place
[1, 2] + [3, 4]          # [1, 2, 3, 4] — concatenate
[0] * 3                  # [0, 0, 0] — repeat (careful with mutable items)

Dictionaries

d = {"name": "Ada", "age": 36}
d["name"]                # 'Ada'
d.get("age")             # 36 — get() returns None for a missing key
d.get("missing", 0)      # 0 — default when the key is absent
d["city"] = "London"     # add or overwrite a key
d.update({"age": 37})    # merge in another dict
"name" in d              # True — key test
d.keys()                 # dict_keys(['name', 'age'])
d.values()               # dict_values(['Ada', 36])
d.items()                # dict_items([('name', 'Ada'), ('age', 36)])
d.pop("age")             # remove a key, return its value
{"a": 1} | {"b": 2}      # {'a': 1, 'b': 2} — merge, right side wins
{k: v * 2 for k, v in {"a": 1}.items()}   # {'a': 2} — dict comprehension

Tuples & sets

t = (1, 2, 3)            # a tuple — like a list, but immutable
a, b, c = t              # unpack: a=1, b=2, c=3
len(t)                   # 3
t[0]                     # 1
# t[0] = 9               # TypeError — tuples cannot be changed

a = {1, 2, 3}; b = {2, 3, 4}
a | b                    # {1, 2, 3, 4} — union
a & b                    # {2, 3} — intersection
a - b                    # {1} — difference
a.add(5)                 # add one element
a.discard(9)             # remove if present — no error if absent
{x * x for x in range(4)}   # {0, 1, 4, 9} — set comprehension

Conditionals & loops

if score >= 90:
    grade = "A"
elif score >= 60:        # elif = "else if"
    grade = "pass"
else:
    grade = "fail"

"big" if x > 3 else "small"   # one-line if: value-if-condition-else-value
1 < 2 < 3                # True — comparisons chain
True and "yes"           # 'yes'    False or "no"  # 'no'

for i in range(3):       # 0, 1, 2 — range stops BEFORE the end
    print(i)
for i in range(0, 10, 3):   # 0, 3, 6, 9
    print(i)
for name in ["Ada", "Grace"]:
    print(name)
for i, name in enumerate(["a", "b"]):   # (0, 'a'), (1, 'b')
    print(i, name)
for a, b in zip([1, 2], ["x", "y"]):    # (1, 'x'), (2, 'y')
    print(a, b)

n = 3
while n > 0:             # runs until the condition is False
    n -= 1
# break exits the loop now; continue skips to the next round

Comprehensions

[x * x for x in range(5)]              # [0, 1, 4, 9, 16]
[x for x in range(10) if x % 2 == 0]   # [0, 2, 4, 6, 8]
[x.upper() for x in ["a", "b"]]        # ['A', 'B']
{k: v * 2 for k, v in {"a": 1}.items()}   # {'a': 2}
{x * x for x in range(4)}              # {0, 1, 4, 9} — set
sum(x * x for x in range(5))           # 30 — generator, no list built
# comprehensions replace most one-line map/filter loops

Functions

def greet(name="world"):       # default argument
    return f"Hello, {name}!"

greet()            # 'Hello, world!'
greet("Ada")       # 'Hello, Ada!'
greet(name="Ada")  # same — keyword argument

def add_all(*args):            # *args: any number of positional args
    return sum(args)
add_all(1, 2, 3)   # 6

def show(**kwargs):            # **kwargs: any number of named args
    return sorted(kwargs)
show(a=1, b=2)     # ['a', 'b']

square = lambda x: x * 2       # a tiny anonymous function
square(21)         # 42
list(map(str, [1, 2]))                     # ['1', '2']
list(filter(lambda x: x > 1, [1, 2, 3]))   # [2, 3]

Files & JSON

with open("data.txt") as f:    # with closes the file for you
    text = f.read()            # whole file as one string
with open("data.txt") as f:
    lines = f.read().splitlines()   # lines without trailing \n

with open("data.txt") as f:
    for line in f:             # iterate line by line (memory-friendly)
        print(line.strip())

with open("out.txt", "w") as f:   # "w" writes (overwrites), "a" appends
    f.write("hello\n")

import json
json.dumps({"a": 1})           # '{"a": 1}' — dict → JSON string
json.loads('{"a": 1}')         # {'a': 1} — JSON string → dict

Exceptions

try:
    n = int("abc")
except ValueError:
    print("not a number")      # runs when int() fails

try:
    1 / 0
except ZeroDivisionError:
    print("cannot divide by zero")
except (ValueError, TypeError):
    print("bad input")
else:
    print("no error — runs only if try succeeded")
finally:
    print("always runs — cleanup goes here")

raise ValueError("bad value")  # raise your own error

Datetime

from datetime import date, datetime, timedelta

date.today()                     # today's date
date(2026, 11, 14)               # a specific date
date(2026, 11, 14).strftime("%Y-%m-%d")   # '2026-11-14'
date(2026, 11, 14) + timedelta(days=7)    # 2026-11-21
datetime.strptime("2026-11-14", "%Y-%m-%d")  # string → datetime
datetime(2026, 11, 14, 9, 30).isoformat()    # '2026-11-14T09:30:00'
# %Y year  %m month  %d day  %H hour  %M minute  %S second

Built-ins worth knowing

sorted(["banana", "kiwi", "fig"], key=len)  # ['fig', 'kiwi', 'banana']
min(["aa", "b"], key=len)        # 'b'
list(reversed([1, 2, 3]))        # [3, 2, 1]
any([False, True])               # True — at least one is true
all([True, True])                # True — every one is true
isinstance(3, int)               # True
type("x")                        # <class 'str'>
hex(255)   # '0xff'    oct(8)   # '0o10'    bin(5)   # '0b101'
len("hello")  # 5    sum([1, 2, 3])  # 6    max([1, 9, 4])  # 9

Gotchas

0.1 + 0.2    # 0.30000000000000004 — floats are binary approximations
round(2.675, 2)   # 2.67, not 2.68 — same reason; use Decimal for money

a = [1, 2, 3]
b = a            # b is the SAME list — changing b changes a
c = a[:]         # a copy — safe to change
c = list(a)      # also a copy

def bad(item, target=[]):        # NEVER use a mutable default — it is shared
    target.append(item)          # between calls!
    return target
def good(item, target=None):     # the safe pattern
    if target is None:
        target = []
    target.append(item)
    return target

1 == True    # True — but 1 is True is False (== is value, is is identity)
"a" is "a"   # usually True — but never rely on is for values

See also

Regex Quick Reference — Python's re module uses the same core syntax. Linux Commands and Git Commands cover the terminal side of a Python workflow. JSON Formatter pretty-prints the JSON your scripts produce.