x = 42 # int
y = 3.14 # float
s = "hello" # str
b = True # bool
n = None # NoneType int("42") # → 42
float("3.14") # → 3.14
str(42) # → "42"
bool(0) # → False
list("abc") # → ['a', 'b', 'c'] Basics Multiple Assignment
a, b, c = 1, 2, 3
a, *rest = [1, 2, 3, 4] # a=1, rest=[2,3,4]
x, y = y, x # swap values name = "Alice"
f"Hello, {name}!" # → "Hello, Alice!"
f"{3.14:.2f}" # → "3.14"
f"{1000000:,}" # → "1,000,000"
f"{'left':<10}" # left-aligned, width 10 Basics Walrus Operator (3.8+)
if n := len(data):
print(f"List has {n} items") Assigns and evaluates in one expression
Basics Ternary (Conditional Expression)
result = "yes" if condition else "no" range(10) # 0–9
range(1, 11) # 1–10
range(0, 10, 2) # 0,2,4,6,8 (step) for i in range(10):
if i == 3: continue # skip 3
if i == 7: break # stop at 7
pass # no-op placeholder first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5 x = 0
def outer():
y = 0
def inner():
global x # modify module-level x
nonlocal y # modify enclosing y
x += 1
y += 1
inner() s = "hello world"
s = 'single quotes'
s = """
multi
line
""" s[0] # 'h'
s[-1] # 'd'
s[2:5] # 'llo'
s[::2] # every 2nd char
s[::-1] # reverse s.upper() # 'HELLO WORLD'
s.lower() # 'hello world'
s.title() # 'Hello World'
s.capitalize() # first char upper
s.swapcase() # swap case of each char s.strip() # remove leading/trailing whitespace
s.lstrip() # remove leading whitespace
s.rstrip() # remove trailing whitespace
s.split(" ") # ['hello', 'world']
s.split(", ", 2) # split max 2 times " ".join(['a', 'b', 'c']) # 'a b c'
"-".join(['x', 'y', 'z']) # 'x-y-z' s.replace("world", "Python") # 'hello Python'
s.find("world") # 6 (index, -1 if not found)
s.index("world") # 6 (raises ValueError if missing)
s.count("l") # 3 Strings Startswith & Endswith
s.startswith("hello") # True
s.endswith("world") # True
s.startswith(("he", "Hi")) # tuple of prefixes Strings Padding & Alignment
s.zfill(10) # zero-pad left
s.center(20, "-") # center with fill char
s.ljust(20, ".") # left-justify
s.rjust(20, ".") # right-justify Strings Validation Methods
s.isdigit() # True if all digits
s.isalpha() # True if all alphabetic
s.isalnum() # True if alphanumeric
s.isupper() # True if all uppercase
s.islower() # True if all lowercase
s.isspace() # True if only whitespace "{} {}".format("hello", "world")
"{0} {1}".format("hello", "world")
"{name}".format(name="Alice")
"%s %d" % ("hello", 42) # old style "hello" * 3 # 'hellohellohello'
"e" in "hello" # True
len("hello") # 5
str.maketrans("aei", "AEI") # translation table lst = [1, 2, 3, 4, 5]
lst = list(range(5)) # [0,1,2,3,4]
lst = [0] * 5 # [0,0,0,0,0]
lst = list("abc") # ['a','b','c'] lst[0] # first item
lst[-1] # last item
lst[1:3] # [2, 3]
lst[::-1] # reversed copy lst.append(6) # add to end
lst.extend([7, 8]) # add multiple items
lst.insert(0, 0) # insert at index 0 lst.remove(3) # remove first occurrence of 3
lst.pop() # remove & return last item
lst.pop(0) # remove & return item at index
lst.clear() # remove all items lst.index(2) # find index of value
lst.count(2) # count occurrences
lst.sort() # sort ascending in place
lst.sort(reverse=True) # sort descending
lst.sort(key=len) # sort by key function
lst.reverse() # reverse in place lst.copy() # shallow copy
sorted(lst) # new sorted list
reversed(lst) # reversed iterator
min(lst), max(lst), sum(lst)
any(lst) # True if any truthy
all(lst) # True if all truthy enumerate(lst) # (index, value) iterator
list(enumerate(['a','b'], 1)) # [(1,'a'),(2,'b')]
zip(lst1, lst2) # pair elements
list(zip([1,2],['a','b'])) # [(1,'a'),(2,'b')] list(map(str, [1,2,3])) # ['1','2','3']
list(filter(lambda x: x>2, [1,2,3,4])) # [3,4]
list(map(lambda x: x**2, range(5))) # [0,1,4,9,16] Dicts & Sets Dict Creation
d = {"key": "value", "num": 42}
d = dict(key="value", num=42)
d = dict.fromkeys(["a","b"], 0) # {'a':0,'b':0} d["key"] # "value" (KeyError if missing)
d.get("key") # "value" (None if missing)
d.get("key", "default") # default if missing d.keys() # all keys
d.values() # all values
d.items() # (key, value) pairs
d.update({"new": 1}) # merge another dict
d.pop("key") # remove key, return value
d.setdefault("x", 0) # set if key missing
d.copy() # shallow copy Dicts & Sets Dict Operations
len(d)
"key" in d # True
del d["key"] # delete key
{**d1, **d2} # merge (Python 3.5+)
d | d2 # merge (Python 3.9+)
d |= d2 # update in-place (3.9+) s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1,2,3} — deduped
s = set() # empty set (not {}) s.add(4) # add element
s.remove(3) # raises KeyError if missing
s.discard(3) # no error if missing
s.pop() # remove/return arbitrary item
s.clear() # remove all Dicts & Sets Set Operations
s1 | s2 # union
s1 & s2 # intersection
s1 - s2 # difference
s1 ^ s2 # symmetric difference
s1.issubset(s2) # True if s1 ⊆ s2
s1.issuperset(s2) # True if s1 ⊇ s2 Comprehensions List Comprehension
[x**2 for x in range(10)]
[x for x in range(10) if x % 2 == 0]
[x*y for x in range(3) for y in range(3)] # nested Comprehensions Dict Comprehension
{k: v for k, v in items.items()}
{x: x**2 for x in range(5)} Comprehensions Set Comprehension
{x**2 for x in range(5)}
{word.lower() for word in words} Comprehensions Generator Expression
sum(x**2 for x in range(10)) # lazy
gen = (x**2 for x in range(10)) # generator object
next(gen) # get next value Use generators for large datasets to save memory
Comprehensions Nested Comprehension
# Flatten a 2D list
[item for row in matrix for item in row]
# Transpose a matrix
[[row[i] for row in matrix] for i in range(4)] 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" Classes Class & Static Methods
@classmethod
def from_string(cls, s):
name, age = s.split(",")
return cls(name, int(age))
@staticmethod
def is_animal(obj):
return isinstance(obj, Animal) def __repr__(self):
return f"Animal(name={self.name!r})"
def __str__(self):
return self.name
def __len__(self): ...
def __eq__(self, other): ...
def __lt__(self, other): ...
def __add__(self, other): ... 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 from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float
label: str = ""
tags: list = field(default_factory=list) Auto-generates __init__, __repr__, __eq__
Classes Context Manager Protocol
class ManagedFile:
def __init__(self, path):
self.path = path
def __enter__(self):
self.f = open(self.path)
return self.f
def __exit__(self, exc_type, exc_val, tb):
self.f.close()
return False # don't suppress exceptions Classes Property Decorator
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be >= 0")
self._radius = value Decorators Simple Decorator
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!") Decorators Decorator with Arguments
def repeat(n):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!") Decorators Built-in Decorators
@property # getter
@name.setter # setter
@staticmethod # no self/cls
@classmethod # cls instead of self
@functools.lru_cache(maxsize=128) # memoize
@functools.cache # Python 3.9+ (unlimited)
@dataclass # auto __init__, __repr__, __eq__
@abstractmethod # from abc module Decorators Class Decorator
def singleton(cls):
instances = {}
@functools.wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Config:
pass with open("file.txt", "r") as f:
content = f.read() # entire file
lines = f.readlines() # list with \n
lines = f.read().splitlines() # clean list File I/O Read Line by Line
with open("file.txt") as f:
for line in f: # memory efficient
print(line.strip()) Best for large files
with open("file.txt", "w") as f:
f.write("hello\n") # write (overwrites)
with open("file.txt", "a") as f:
f.write("new line\n") # append "r" # read (default)
"w" # write (overwrites)
"a" # append
"rb" # read binary
"wb" # write binary
"r+" # read + write
"x" # exclusive create (fails if exists) import json
data = json.loads('{"key": "value"}') # str → dict
text = json.dumps(data, indent=2) # dict → str
with open("data.json") as f:
data = json.load(f) # file → dict
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # dict → file from pathlib import Path
p = Path("dir/file.txt")
p.exists() # True/False
p.parent # Path("dir")
p.name # "file.txt"
p.stem # "file"
p.suffix # ".txt"
p.read_text() # read entire file
p.write_text("hi") # write file
p.mkdir(parents=True, exist_ok=True)
list(p.glob("*.py")) # find files import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"])
with open("out.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name","age"])
writer.writeheader()
writer.writerow({"name": "Alice", "age": 30}) type(x) # <class 'int'>
isinstance(x, int) # True/False
isinstance(x, (int, str)) # check multiple types
issubclass(Dog, Animal) # True abs(-5) # 5
round(3.14159, 2) # 3.14
pow(2, 10) # 1024
divmod(17, 5) # (3, 2) — quotient + remainder
min(1, 2, 3) # 1
max([1, 2, 3]) # 3
sum([1, 2, 3]) # 6 Built-ins Iteration Built-ins
zip([1,2], ['a','b']) # (1,'a'), (2,'b')
enumerate(['a','b'], start=1) # (1,'a'), (2,'b')
map(str, [1,2,3]) # lazy map
filter(None, [0,"",1,"x"]) # truthy values
sorted([3,1,2], reverse=True) # [3,2,1]
reversed([1,2,3]) # lazy iterator repr(obj) # debug string (__repr__)
str(obj) # user string (__str__)
print(*[1,2,3], sep=", ", end="\n")
input("Enter: ") # read stdin Built-ins Object Introspection
dir(obj) # list attributes/methods
vars(obj) # object's __dict__
help(str) # docstring
hasattr(obj, "attr")
getattr(obj, "attr", default)
setattr(obj, "attr", value)
delattr(obj, "attr")
id(obj) # memory address
hash(obj) # hash value Built-ins Functional Built-ins
any([False, True, False]) # True
all([True, True, True]) # True
next(iter([1,2,3])) # 1
list(range(5)) # [0,1,2,3,4]
chr(65) # 'A'
ord('A') # 65
bin(10), oct(10), hex(10) # '0b1010','0o12','0xa' Error Handling Basic try/except
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Type or value error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No error") # runs if no exception
finally:
print("Always runs") # cleanup Error Handling Raise Exceptions
raise ValueError("invalid input")
raise ValueError("bad value") from original # chaining
raise # re-raise current exception Error Handling Custom Exceptions
class AppError(Exception):
def __init__(self, message, code=None):
super().__init__(message)
self.code = code
try:
raise AppError("not found", code=404)
except AppError as e:
print(e.code) # 404 Error Handling Context Manager (contextmanager)
from contextlib import contextmanager
@contextmanager
def managed_resource():
resource = acquire()
try:
yield resource
finally:
release(resource)
with managed_resource() as r:
use(r) Error Handling Common Exceptions
ValueError # bad value type/range
TypeError # wrong type
KeyError # missing dict key
IndexError # list index out of range
AttributeError # object has no attribute
FileNotFoundError # file not found
PermissionError # access denied
OSError # OS-level error
RuntimeError # generic runtime error
StopIteration # iterator exhausted
RecursionError # max recursion depth
NotImplementedError # method not implemented
AssertionError # assert statement failed Error Handling Assert Statement
assert condition, "Error message"
assert len(data) > 0, "Data cannot be empty"
assert isinstance(x, int), f"Expected int, got {type(x)}" Disabled with python -O flag — don't use for user validation