Python Cheatsheet
Python Basics
Use this Python reference while you build software engineering projects, review code, or refresh the syntax you reach for most.
Variables and Assignment
Python is dynamically typed; no declaration needed.
x = 10 name = "Alice" pi = 3.14 is_active = True nothing = None # Multiple assignment a, b, c = 1, 2, 3 a = b = c = 0 # Augmented assignment x += 5; x -= 2; x *= 3; x /= 4; x //= 2; x %= 3; x **= 2; x &= 0b1111; x |= 1; x ^= 2
Built-in Types
| Type | Example | Notes |
|---|---|---|
int | 42, -7, 0xFF, 0b1010, 0o17 | Arbitrary precision |
float | 3.14, 2.5e-3, float('inf') | IEEE 754 double |
complex | 3+4j, complex(3, 4) | .real, .imag attrs |
bool | True, False | Subclass of int |
str | 'hello', "world", '''multi''' | Immutable |
bytes | b'hello', bytes(5) | Immutable byte sequence |
bytearray | bytearray(b'hi') | Mutable byte sequence |
NoneType | None | Singleton |
list | [1, 2, 3] | Mutable sequence |
tuple | (1, 2, 3) | Immutable sequence |
dict | {"a": 1} | Key-value map (ordered 3.7+) |
set | {1, 2, 3} | Unordered unique elements |
frozenset | frozenset({1, 2}) | Immutable set |
Type Conversion
int("42") # 42 int(3.9) # 3 (truncates, does not round) int("ff", 16) # 255 (base 16) int("0b101", 2) # 5 float("3.14") # 3.14 str(100) # "100" bool(0) # False bool("") # False bool([]) # False list("abc") # ['a', 'b', 'c'] tuple([1, 2]) # (1, 2) set([1, 1, 2]) # {1, 2} bytes([65, 66]) # b'AB' chr(65) # 'A' ord('A') # 65
Falsy values: None, False, 0, 0.0, 0j, "", b"", [], (), {}, set(), frozenset()
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 3 + 2 → 5 |
- | Subtraction | 3 - 2 → 1 |
* | Multiplication | 3 * 2 → 6 |
/ | True division (always float) | 7 / 2 → 3.5 |
// | Floor division | 7 // 2 → 3 |
% | Modulo | 7 % 2 → 1 |
** | Exponentiation | 2 ** 8 → 256 |
-x | Unary negation | -(-3) → 3 |
abs(x) | Absolute value | abs(-5) → 5 |
divmod(a, b) | (quotient, remainder) | divmod(7, 2) → (3, 1) |
Note:
-10 % 3is2in Python (result always has sign of divisor).7 // -2is-4(rounds toward negative infinity).
Comparison and Boolean Operators
# Comparison — always return bool x == y; x != y; x < y; x <= y; x > y; x >= y # Identity (object sameness, not value equality) x is None # True if x IS None x is not None a is b # True only if same object in memory # Membership "a" in "cat" # True 3 in [1, 2, 3] # True 5 not in range(3) # True # Chained comparisons 1 < x < 10 # equivalent to (1 < x) and (x < 10) 0 <= i < len(lst) # Boolean (short-circuit evaluation) True and False # False — stops at first False True or False # True — stops at first True not True # False # Short-circuit returns the deciding operand (not just bool) None or "default" # "default" "value" or "other" # "value" x and x.strip() # safe: only calls .strip() if x is truthy
Bitwise Operators
a & b # AND 5 & 3 → 1 a | b # OR 5 | 3 → 7 a ^ b # XOR 5 ^ 3 → 6 ~a # NOT ~5 → -6 a << n # left shift 1 << 4 → 16 a >> n # right shift 16 >> 2 → 4
String Literals
s1 = 'single' s2 = "double" s3 = '''triple single''' s4 = """triple double""" # Raw strings — no escape processing path = r"C:\Users\name\docs" # f-strings (Python 3.6+) — embed expressions name = "Alice" f"Hello, {name}!" # "Hello, Alice!" f"{3.14159:.2f}" # "3.14" f"{1_000_000:,}" # "1,000,000" f"{x!r}" # repr(x) f"{x!s}" # str(x) f"{'center':^20}" # centered in 20 chars # Byte strings b"bytes literal" rb"raw bytes \n" # raw + bytes # Escape sequences "\n" # newline "\t" # tab "\r" # carriage return "\\" # backslash "\'" # single quote "\"" # double quote "\0" # null "\x41" # hex → 'A' "A" # unicode 4-hex → 'A' "\U00000041" # unicode 8-hex → 'A'
Built-in Functions (core)
| Function | Description | Example |
|---|---|---|
print(*args, sep, end, file) | Output to stdout | print("a", "b", sep="-") |
input(prompt) | Read line from stdin | input("Name: ") → str |
len(obj) | Length / size | len([1,2,3]) → 3 |
type(obj) | Type of object | type(42) → <class 'int'> |
isinstance(obj, cls) | Type check (preferred) | isinstance(1, int) → True |
issubclass(cls, base) | Subclass check | issubclass(bool, int) → True |
id(obj) | Memory address as int | id(x) |
hash(obj) | Hash value | hash("abc") |
dir(obj) | List attributes/methods | dir([]) |
help(obj) | Interactive help | help(str.split) |
repr(obj) | Unambiguous string | repr("hi") → "'hi'" |
vars(obj) | __dict__ of object | vars(instance) |
callable(obj) | Is it callable? | callable(print) → True |
getattr(obj, name, default) | Get attribute by name | getattr(x, "y", None) |
setattr(obj, name, val) | Set attribute by name | setattr(x, "y", 5) |
hasattr(obj, name) | Has attribute? | hasattr(x, "__len__") |
delattr(obj, name) | Delete attribute | delattr(x, "y") |
eval(expr) | Evaluate expression string | eval("1+2") → 3 |
exec(code) | Execute code string | exec("x=1") |
compile(src, ...) | Compile to code object | advanced |
Numeric Built-ins
abs(-5) # 5 round(3.567, 2) # 3.57 round(2.5) # 2 (banker's rounding — rounds to even!) round(3.5) # 4 min(3, 1, 2) # 1 max(3, 1, 2) # 3 min([3, 1, 2]) # 1 (also accepts iterable) sum([1, 2, 3]) # 6 sum([1, 2], 10) # 13 (with start value) pow(2, 10) # 1024 pow(2, 10, 1000) # 24 (modular exponentiation, very fast) import math math.floor(3.7) # 3 math.ceil(3.2) # 4 math.trunc(3.9) # 3 math.sqrt(16) # 4.0 math.log(100, 10) # 2.0 math.log2(8) # 3.0 math.log10(1000) # 3.0 math.exp(1) # 2.718... math.pi # 3.14159... math.e # 2.71828... math.inf # float infinity math.nan # not-a-number math.isnan(x) # True if NaN math.isinf(x) # True if infinite math.gcd(12, 8) # 4 math.lcm(4, 6) # 12 (Python 3.9+) math.factorial(5) # 120 math.comb(10, 3) # 120 (combinations, Python 3.8+) math.perm(10, 3) # 720 (permutations, Python 3.8+)
Walrus Operator (:=)
Assigns and returns a value in one expression (Python 3.8+).
if n := len(data): print(f"{n} items found") while chunk := file.read(1024): process(chunk) results = [y for x in data if (y := transform(x)) is not None]
Scope (LEGB Rule)
| Scope | Meaning |
|---|---|
| Local | Inside the current function |
| Enclosing | In enclosing function (closures) |
| Global | Module-level names |
| Built-in | Python builtins (len, print, etc.) |
x = "global" def outer(): x = "enclosing" def inner(): nonlocal x # modify enclosing scope variable x = "modified-enclosing" inner() def modifier(): global x # modify module-level variable x = "modified-global"
del Statement
del x # remove variable from namespace del lst[2] # remove element at index del lst[1:3] # remove slice del dct["key"] # remove dict entry del obj.attr # remove attribute
Comments and Docstrings