Python
Variables & Types
x = 10—Assign variable (dynamic typing)
type(x)—Get type of variable
int / float / str / bool—Primitive types
int("42")—Type casting to integer
isinstance(x, int)—Type check
None—Null value equivalent
x, y = 1, 2—Multiple assignment
f"Hello {name}"—F-string interpolation
String Methods
.strip()—Remove leading/trailing whitespace
.split(sep)—Split into list
.join(list)—Join list into string
.replace(old, new)—Replace substring
.find(sub)—Index of substring (-1 if not found)
.startswith() / .endswith()—Check prefix/suffix
.upper() / .lower()—Case conversion
.format()—String formatting
.isdigit()—Check if all digits
len(s)—String length
Lists
lst = [1, 2, 3]—Create a list
lst[0] / lst[-1]—Index from start/end
lst[1:3]—Slice (index 1 to 2)
.append(x)—Add to end
.extend(lst2)—Add all items from another list
.insert(i, x)—Insert at index
.pop(i)—Remove & return at index
.remove(x)—Remove first occurrence
.sort() / sorted()—Sort in-place / new list
.reverse()—Reverse in-place
[x for x in lst if cond]—List comprehension
len(lst)—Number of elements
Dictionaries
d = {"k": "v"}—Create dictionary
d["key"]—Access value (KeyError if missing)
d.get("key", default)—Safe access with default
d.keys() / d.values()—View keys / values
d.items()—Key-value pairs
d.update(d2)—Merge another dict
d.pop("key")—Remove and return value
"key" in d—Check if key exists
{k: v for k, v in ...}—Dict comprehension
d | d2—Merge dicts (3.9+)
Control Flow
if / elif / else—Conditional branching
for x in iterable:—For loop
while condition:—While loop
for i in range(n):—Loop n times
for i, v in enumerate(lst):—Loop with index
for k, v in d.items():—Loop over dict
break / continue—Exit or skip iteration
x if cond else y—Ternary expression
match val: case ...—Pattern matching (3.10+)
Functions
def fn(a, b):—Define function
def fn(a, b=5):—Default argument
def fn(*args):—Variable positional args
def fn(**kwargs):—Variable keyword args
return value—Return from function
lambda x: x * 2—Anonymous function
def fn() -> int:—Return type hint
@decorator—Function decorator
yield value—Generator function
Classes & OOP
class MyClass:—Define a class
def __init__(self):—Constructor method
self.attr = val—Instance attribute
class B(A):—Inheritance
super().__init__()—Call parent constructor
@staticmethod—No self/cls reference
@classmethod—Takes cls as first arg
@property—Getter decorator
__str__ / __repr__—String representation
__len__ / __getitem__—Dunder methods for len/indexing
Error Handling
try: / except:—Catch exceptions
except ValueError as e:—Catch specific error
finally:—Always executes
raise Exception(msg)—Raise an error
assert cond, msg—Assert condition
with open() as f:—Context manager
Common Built-ins
print()—Output to console
input()—Read user input
range(n)—Sequence 0 to n-1
len()—Length of collection
max() / min()—Largest / smallest
sum()—Sum of iterable
abs()—Absolute value
round()—Round number
zip(a, b)—Pair up iterables
map(fn, lst)—Apply fn to each
filter(fn, lst)—Keep matching items
any() / all()—Test iterable booleans
File & Modules
import module—Import entire module
from mod import func—Import specific name
open("f.txt", "r")—Open file for reading
f.read() / f.readlines()—Read file content
f.write(data)—Write to file
import json—JSON parsing module
json.loads(s) / json.dumps(o)—Parse / serialize JSON
os.path.join()—Join file paths safely
allprintabledoc.com