🐍 Python Cheatsheet
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) # TrueStrings
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 whitespaceLists
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 * 2Files
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.