Python Cheatsheet
Languages
17 views
Apr 2026
Python Cheatsheet
Data Types & Variables
# Numbers
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
# Strings
s = "hello"
s2 = 'world'
multi = """multi
line"""
# Boolean
t = True
f = False
# None
n = None
# Type checking / conversion
type(x) # <class 'int'>
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
String Operations
s = "Hello, World!"
s.upper() # "HELLO, WORLD!"
s.lower() # "hello, world!"
s.strip() # trim whitespace
s.replace("o","0") # "Hell0, W0rld!"
s.split(", ") # ["Hello", "World!"]
s.startswith("He") # True
s.endswith("!") # True
s.find("World") # 7
len(s) # 13
# f-strings (Python 3.6+)
name = "Alice"
age = 30
print(f"{name} is {age} years old")
# Format
"{:.2f}".format(3.14159) # "3.14"
f"{3.14159:.2f}" # "3.14"
Collections
# List — ordered, mutable
lst = [1, 2, 3, 4]
lst.append(5) # [1,2,3,4,5]
lst.insert(0, 0) # [0,1,2,3,4,5]
lst.remove(3) # removes first 3
lst.pop() # removes & returns last
lst.sort()
lst.reverse()
lst[1:3] # slice [1,2]
# Tuple — ordered, immutable
t = (1, 2, 3)
t[0] # 1
# Set — unordered, unique
s = {1, 2, 3, 2} # {1, 2, 3}
s.add(4)
s.discard(1)
a | b # union
a & b # intersection
a - b # difference
# Dictionary — key-value
d = {"name": "Alice", "age": 30}
d["name"] # "Alice"
d.get("missing", "default")
d.keys()
d.values()
d.items()
d.update({"city": "NYC"})
del d["age"]
Control Flow
# if / elif / else
x = 10
if x > 0:
print("positive")
elif x == 0:
print("zero")
else:
print("negative")
# Ternary
result = "yes" if x > 0 else "no"
# for loop
for i in range(5): # 0..4
print(i)
for i in range(2, 10, 2): # 2,4,6,8
print(i)
for item in ["a","b","c"]:
print(item)
for i, v in enumerate(["a","b","c"]):
print(i, v) # 0 a, 1 b, 2 c
# while loop
n = 0
while n < 5:
n += 1
# break / continue / else on loop
for i in range(10):
if i == 3: continue
if i == 7: break
else:
print("loop finished without break")
Functions
# Basic
def greet(name):
return f"Hello, {name}!"
# Default args
def power(base, exp=2):
return base ** exp
# *args and **kwargs
def total(*args):
return sum(args)
def info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")
# Lambda
square = lambda x: x ** 2
# Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
# Generators
def countdown(n):
while n > 0:
yield n
n -= 1
# Decorators
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@my_decorator
def say_hi():
print("Hi!")
List Comprehensions
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
# Dict comprehension
d = {k: v for k, v in zip("abc", [1,2,3])}
# Set comprehension
unique = {x % 3 for x in range(10)}
# Generator expression (lazy)
gen = (x**2 for x in range(100))
Classes & OOP
class Animal:
species = "Unknown" # class variable
def __init__(self, name, age):
self.name = name # instance variable
self.age = age
def speak(self):
return f"{self.name} makes a sound"
@classmethod
def get_species(cls):
return cls.species
@staticmethod
def is_animal():
return True
def __str__(self):
return f"Animal({self.name})"
def __repr__(self):
return f"Animal({self.name!r}, {self.age!r})"
# Inheritance
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
# Dataclass (Python 3.7+)
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type/Value error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No error occurred")
finally:
print("Always runs")
# Raise
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Custom exception
class AppError(Exception):
def __init__(self, msg, code):
super().__init__(msg)
self.code = code
File I/O
# Read
with open("file.txt", "r") as f:
content = f.read() # entire file
lines = f.readlines() # list of lines
# Write
with open("file.txt", "w") as f:
f.write("Hello\n")
# Append
with open("file.txt", "a") as f:
f.write("More content\n")
# JSON
import json
data = {"key": "value"}
json_str = json.dumps(data, indent=2)
obj = json.loads(json_str)
with open("data.json", "w") as f:
json.dump(data, f)
with open("data.json") as f:
data = json.load(f)
Useful Built-ins & Libraries
# Built-ins
abs(-5) # 5
round(3.567, 2) # 3.57
max([1,2,3]) # 3
min([1,2,3]) # 1
sum([1,2,3]) # 6
sorted([3,1,2]) # [1,2,3]
reversed([1,2,3]) # iterator
zip([1,2],[3,4]) # [(1,3),(2,4)]
map(str, [1,2,3]) # ["1","2","3"]
filter(None, [0,1,2,False,3]) # [1,2,3]
any([False, True]) # True
all([True, True]) # True
# os / pathlib
import os
from pathlib import Path
os.getcwd()
Path("dir/file.txt").exists()
Path("dir").mkdir(parents=True, exist_ok=True)
# datetime
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today().date()
delta = timedelta(days=7)
next_week = now + delta
fmt = now.strftime("%Y-%m-%d %H:%M")
# random
import random
random.random() # 0.0 – 1.0
random.randint(1, 10)
random.choice([1,2,3])
random.shuffle(lst)