Some links in this article are affiliate links. We earn a commission at no extra cost to you when you purchase through them. Full disclosure.
Click any item to expand with examples. Want to go deeper? Read the complete Python guide or check out the pip cheat sheet for package management.
📦 Variables & Types
Variables & assignment basics
name = "Alice" # string age = 30 # int price = 9.99 # float active = True # bool items = None # NoneTypeMultiple assignment
x, y, z = 1, 2, 3 a = b = c = 0
Type checking
type(name) # <class ‘str’> isinstance(age, int) # True
f-strings (formatted strings) essential
name = "Alice" age = 30f”Hello, {name}!” # Hello, Alice! f”{name} is {age} years old” # Alice is 30 years old f”{price:.2f}” # 9.99 (2 decimal places) f”{1000000:,}” # 1,000,000 f”{‘hello’:>10}” # ’ hello’ (right-align) f”{‘hello’:^10}” # ’ hello ’ (center) f”{name!r}” # ‘Alice’ (with quotes)
String methods essential
s = "Hello, World!"s.lower() # “hello, world!” s.upper() # “HELLO, WORLD!” s.strip() # remove whitespace from both ends s.split(”, ”) # [“Hello”, “World!”] s.replace(“World”, “Python”) # “Hello, Python!” s.startswith(“Hello”) # True s.endswith(”!”) # True s.find(“World”) # 7 (index, -1 if not found) s.count(“l”) # 3 ” “.join([“a”, “b”]) # “a b” s.isdigit() # False s[0:5] # “Hello” (slicing)
Type conversion basics
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
bool(0) # False
bool("") # False
bool("anything") # True
list("abc") # ['a', 'b', 'c']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 1, 2, 3]) # {1, 2, 3}
📋 Lists
Creating & accessing essential
nums = [1, 2, 3, 4, 5] mixed = [1, "two", 3.0, True]nums[0] # 1 (first) nums[-1] # 5 (last) nums[1:3] # [2, 3] (slice) nums[:3] # [1, 2, 3] nums[::2] # [1, 3, 5] (every 2nd) nums[::-1] # [5, 4, 3, 2, 1] (reversed) len(nums) # 5
List methods essential
nums = [1, 2, 3]nums.append(4) # [1, 2, 3, 4] nums.insert(0, 0) # [0, 1, 2, 3, 4] nums.extend([5, 6]) # [0, 1, 2, 3, 4, 5, 6] nums.remove(0) # removes first occurrence nums.pop() # removes & returns last nums.pop(0) # removes & returns index 0 nums.sort() # sort in place nums.sort(reverse=True) # descending nums.reverse() # reverse in place nums.index(3) # find index of value nums.count(2) # count occurrences nums.copy() # shallow copy
List comprehensions essential
# Basic squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]With condition
evens = [x for x in range(20) if x % 2 == 0]
Transform
names = [“alice”, “bob”] upper = [n.upper() for n in names]
Nested
matrix = [[1,2],[3,4]] flat = [x for row in matrix for x in row] # [1,2,3,4]
With else
labels = [“even” if x%2==0 else “odd” for x in range(5)]
📖 Dictionaries
Creating & accessing essential
user = {"name": "Alice", "age": 30, "active": True}
user[“name”] # “Alice”
user.get(“email”, “N/A”) # “N/A” (default if missing)
user[“email”] = “a@b.com” # add/update
del user[“active”] # delete key
“name” in user # True
len(user) # number of keys
Dict methods essential
d = {"a": 1, "b": 2}
d.keys() # dict_keys([‘a’, ‘b’])
d.values() # dict_values([1, 2])
d.items() # dict_items([(‘a’, 1), (‘b’, 2)])
d.update({“c”: 3}) # merge another dict
d.pop(“a”) # remove & return value
d.setdefault(“d”, 4) # set if missing, return value
Dict comprehension
squares = {x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Merge (Python 3.9+)
merged = {**d, **{“e”: 5}}
merged = d | {“e”: 5} # Python 3.9+
🔄 Control Flow
if / elif / else basics
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
Ternary
status = “adult” if age >= 18 else “minor”
Match statement (Python 3.10+)
match command:
case “quit”:
exit()
case “hello”:
print(“Hi!”)
case _:
print(“Unknown”)
Loops essential
# For loop for i in range(5): # 0, 1, 2, 3, 4 for i in range(2, 10, 2): # 2, 4, 6, 8 for item in my_list: for i, item in enumerate(my_list): # with index for key, val in my_dict.items():While loop
while condition: do_something()
Loop control
break # exit loop continue # skip to next iteration
Else clause (runs if loop completes without break)
for item in items: if item == target: break else: print(“Not found”)
⚡ Functions
Defining functions essential
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet(“Alice”) # “Hello, Alice!”
greet(“Bob”, “Hi”) # “Hi, Bob!”
*args and **kwargs
def func(*args, **kwargs):
print(args) # tuple of positional args
print(kwargs) # dict of keyword args
func(1, 2, name=“Alice”)
(1, 2)
{‘name’: ‘Alice’}
Lambda
square = lambda x: x**2
sorted(users, key=lambda u: u[“age”])
Decorators advanced
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.2f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
slow_function() # “slow_function took 1.00s”
🏗️ Classes
Basic class essential
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
def __str__(self):
return f"User({self.name}, {self.age})"
def __repr__(self):
return f"User('{self.name}', {self.age})"
user = User(“Alice”, 30)
print(user.greet()) # “Hi, I’m Alice”
Dataclasses (Python 3.7+) modern
from dataclasses import dataclass@dataclass class User: name: str age: int active: bool = True
user = User(“Alice”, 30)
Auto-generates init, repr, eq
📁 File I/O
Reading & writing files essential
# Read entire file
with open("file.txt", "r") as f:
content = f.read()
Read lines
with open(“file.txt”) as f:
lines = f.readlines() # list of lines
# or
for line in f:
print(line.strip())
Write
with open(“file.txt”, “w”) as f:
f.write(“Hello\n”)
Append
with open(“file.txt”, “a”) as f:
f.write(“More text\n”)
JSON
import json
with open(“data.json”) as f:
data = json.load(f)
with open(“data.json”, “w”) as f:
json.dump(data, f, indent=2)
⚠️ Error Handling
try / except / finally essential
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero")
except (TypeError, ValueError) as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No error occurred")
finally:
print("Always runs")
Raise exceptions
raise ValueError(“Invalid input”)
Custom exceptions
class MyError(Exception):
pass
📦 Common Modules
os & pathlib useful
import os from pathlib import Pathos.getcwd() # current directory os.listdir(”.”) # list files os.path.exists(“file.txt”) # check if exists os.makedirs(“dir/sub”, exist_ok=True) os.environ.get(“API_KEY”, "") # env variable
Pathlib (modern, preferred)
p = Path(“src/app.py”) p.exists() # True/False p.read_text() # read file p.write_text(“content”) # write file p.parent # Path(‘src’) p.stem # ‘app’ p.suffix # ‘.py’ list(Path(”.“).glob(”**/*.py”)) # find all .py files
datetime useful
from datetime import datetime, timedeltanow = datetime.now() today = datetime.today().date() ts = datetime.fromtimestamp(1710374400)
now.strftime(“%Y-%m-%d %H:%M”) # “2026-03-14 10:30” datetime.strptime(“2026-03-14”, “%Y-%m-%d”)
tomorrow = now + timedelta(days=1) diff = datetime(2026, 12, 31) - now # timedelta object
re ([regex](/blog/regex-tester/)) useful
import rere.search(r”\d+”, “age: 30”) # match object re.findall(r”\d+”, “1 and 2 and 3”) # [‘1’, ‘2’, ‘3’] re.sub(r”\s+”, ” ”, “too many”) # “too many” re.split(r”[,;]”, “a,b;c”) # [‘a’, ‘b’, ‘c’]
match = re.search(r”(\w+)@(\w+)”, “user@host”) match.group(1) # “user” match.group(2) # “host”
Quick Reference
| What you want to do | Code |
|---|---|
print(f"Hello {name}") | |
| Input | name = input("Name: ") |
| Length | len(my_list) |
| Range | range(start, stop, step) |
| Sort | sorted(items, key=func) |
| Enumerate | for i, x in enumerate(items): |
| Zip | for a, b in zip(list1, list2): |
| Map | list(map(func, items)) |
| Filter | list(filter(func, items)) |
| Any/All | any(items) / all(items) |
| Min/Max | min(items) / max(items) |
| Sum | sum(items) |
| Unique | list(set(items)) |
| Flatten | [x for sub in nested for x in sub] |
| Dict from lists | dict(zip(keys, values)) |
Quick access: Raycast lets you search commands, snippets, and cheat sheets instantly from your keyboard. Free for Mac.
Related: Bash Cheat Sheet · Best AI Engineering Courses · How to Run DeepSeek Locally