PyPython · Lesson 14 of 14

Python Cheatsheet

The whole language on one page — syntax, collections, idioms. Bookmark this.

Python
# ── Basics ──────────────────────────────
x = 42                      # int
pi = 3.14                   # float
name = "Ada"                # str
ok = True                   # bool
nothing = None
f"{name} is {x}"            # f-string interpolation
x, y = y, x                 # swap

# ── Control flow ────────────────────────
if x > 10:      ...
elif x > 5:     ...
else:           ...

for i in range(5): ...          # 0..4
for i, v in enumerate(items): ...
while cond: ...
result = "big" if x > 10 else "small"

# ── Functions ───────────────────────────
def greet(name, punct="!"):
    return f"Hi {name}{punct}"
def total(*args, **kwargs): ...
square = lambda n: n * n
Python
# ── Collections ─────────────────────────
nums = [3, 1, 4]                 # list (mutable)
nums.append(1); nums.sort(); nums[0]; nums[-1]; nums[1:3]
point = (3, 4)                   # tuple (immutable)
ages = {"Ada": 17, "Bob": 15}    # dict
ages.get("Eve", 0); ages.items(); ages.keys()
seen = {1, 2, 3}                 # set
[n * 2 for n in nums if n > 1]   # comprehension
{k: v for k, v in pairs}         # dict comprehension

# ── Strings ─────────────────────────────
s.upper() .lower() .strip() .split(",") .replace(a, b)
",".join(items); s.startswith("py"); "x" in s; len(s)

# ── Files & errors ──────────────────────
with open("f.txt") as f:
    data = f.read()              # .readlines() for a list
try:
    risky()
except ValueError as e:
    handle(e)
finally:
    cleanup()

# ── Classes ─────────────────────────────
class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        return f"{self.name} says woof"

# ── Common stdlib ───────────────────────
import json, os, sys, re, math, random
json.dumps(obj); json.loads(text)
random.randint(1, 6); math.floor(x)
sorted(items, key=lambda x: x.age, reverse=True)
min(nums); max(nums); sum(nums); abs(-5)