🐍 Python Cheatsheet

📌 Python reference✍️ Written by Mark Sullivan📅 Reviewed 2026-04-21⏱ ~5 min read

A one-page reference for the Python syntax you'll use 80% of the time. Press Ctrl + P to save as PDF — the print stylesheet hides everything except the code.

Variables & Types

python
x = 42                    # int
y = 3.14                  # float
s = 'hello'               # str
b = True                  # bool (capitalized)
xs = [1, 2, 3]            # list
user = {'name': 'Aisha'}  # dict
nothing = None            # None

# Type checks
type(x)                   # <class 'int'>
isinstance(x, int)        # True

Strings

python
name = 'Aisha'
f'Hello, {name}'           # f-string
name.upper()               # 'AISHA'
name.lower()
name.replace('A', 'B')
name.split(',')
','.join(['a','b'])
len(name)
'is' in name              # substring check
name.strip()              # trim whitespace

Lists

python
xs = [1, 2, 3]
xs.append(4)
xs.pop()
xs[0]; xs[-1]             # first, last
xs[1:3]                   # slice
len(xs)
sorted(xs)
[n*2 for n in xs]         # comprehension
[n for n in xs if n > 1]

Dicts

python
user = {'name': 'Aisha', 'age': 30}
user['name']
user.get('email', 'none')
user['age'] = 31
user.keys(); user.values(); user.items()
'age' in user             # key check
del user['age']

Conditionals

python
if x > 0:
    pass
elif x == 0:
    pass
else:
    pass

# Ternary
status = 'adult' if age >= 18 else 'minor'

# Match (3.10+)
match day:
    case 'Sat' | 'Sun': print('weekend')
    case _: print('weekday')

Loops

python
for i in range(5):       # 0..4
    print(i)

for name in names:
    print(name)

while cond:
    do_thing()

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

Functions

python
def greet(name, greeting='Hello'):
    return f'{greeting}, {name}!'

greet('Aisha')
greet('Aisha', greeting='Hi')

# Lambda
double = lambda x: x * 2

Files

python
with open('data.txt') as f:
    contents = f.read()

with open('out.txt', 'w') as f:
    f.write('saved')

# Line by line
for line in open('data.txt'):
    print(line.strip())

Classes

python
class User:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return f'Hi, {self.name}'

u = User('Aisha')
u.greet()
📌
Need the concepts?

This is a syntax reference, not a tutorial. Each row maps to a concept lesson — start with the 13 concepts if anything here is unfamiliar.

M
Mark Sullivan
Lead writer · 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark →