Free JYnapse Knowledge Base · Cheat Sheet

Python Cheat Sheet

The core of the language on one page — types, collections, loops, functions and the patterns you use every day. Python 3.

For Beginners · analysts · automators Level Beginner → Intermediate Languages EN · BM · 中文 on request

1 Variables & types

n   = 42            # int
pi  = 3.14          # float
name = "JY"         # str
ok  = True          # bool
none = None         # absence of value

type(n)             # <class 'int'>
int("7"), str(7)    # convert
f"{name} has {n}"   # f-string

Python is dynamically typed — no declarations. Names are just labels pointing at objects.

2 Strings

s = "Hello, World"
s.lower()           # 'hello, world'
s.upper().strip()
s.replace("l", "L")
s.split(",")        # ['Hello', ' World']
",".join(["a","b"]) # 'a,b'
s[0], s[-1], s[0:5] # index & slice
"World" in s        # True
len(s)

Strings are immutable — every method returns a new string.

3 Lists

xs = [3, 1, 2]
xs.append(4)        # add to end
xs.insert(0, 9)
xs.pop()            # remove & return last
xs.sort()           # in place
sorted(xs, reverse=True)
xs[1:3]             # slice
xs[::-1]            # reversed copy
len(xs); sum(xs); max(xs)

b = a copies the reference, not the list. Use b = a.copy() for a separate one.

4 Dicts & sets

d = {"name": "JY", "age": 30}
d["name"]           # 'JY'
d.get("email", "—") # default if missing
d["email"] = "a@b.c"
d.keys(); d.values(); d.items()
"name" in d         # True

st = {1, 2, 2, 3}   # {1, 2, 3} — unique
st & {2,3}; st | {4}# intersect / union

5 Control flow

if score >= 80:
    grade = "A"
elif score >= 50:
    grade = "B"
else:
    grade = "F"

for i, x in enumerate(xs):
    print(i, x)

for k, v in d.items():
    print(k, v)

while n > 0:
    n -= 1              # break / continue

Indentation is the syntax — 4 spaces per level, consistently.

6 Functions

def greet(name, greeting="Hi"):
    return f"{greeting}, {name}"

greet("JY")                 # 'Hi, JY'
greet("JY", greeting="Yo")  # keyword arg

def total(*nums, **opts):   # var args
    return sum(nums)

square = lambda x: x * x    # anonymous

Never use a mutable default (def f(x=[])) — it's shared across calls. Use None then create inside.

7 Comprehensions

The Pythonic way to build a collection from another in one line.

[x*x for x in range(5)]        # [0,1,4,9,16]
[x for x in xs if x > 1]       # filter
{k: v*2 for k, v in d.items()} # dict
{c for c in "banana"}          # set of chars
[(i, x) for i, x in enumerate(xs)]

Readable beats clever — if a comprehension needs two ifs and a nested loop, write a normal loop instead.

8 Files & errors

with open("data.txt") as f:      # auto-closes
    text = f.read()
    lines = f.readlines()

with open("out.txt", "w") as f:
    f.write("hello\n")

try:
    risky()
except ValueError as e:
    print("bad value:", e)
except Exception as e:
    print("other:", e)
finally:
    cleanup()

9 Useful built-ins

range(5)0…4 sequence
enumerate(xs)index + value
zip(a, b)pair two lists
map(fn, xs)apply to each
filter(fn, xs)keep where true
any / alltrue if any / all
sorted(xs, key=…)sort by rule
round / abs / minmaths

10 Modules & standard library

import math, random, json
from datetime import datetime
from collections import Counter

math.sqrt(16)                 # 4.0
random.choice(xs)
Counter("banana")             # {'a':3,...}
json.dumps({"a": 1})          # to JSON str
datetime.now().year

Batteries included — before pip install, check if the standard library already does it (os, pathlib, csv, re, itertools).