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

TypeExampleNotes
int42, -7, 0xFF, 0b1010, 0o17Arbitrary precision
float3.14, 2.5e-3, float('inf')IEEE 754 double
complex3+4j, complex(3, 4).real, .imag attrs
boolTrue, FalseSubclass of int
str'hello', "world", '''multi'''Immutable
bytesb'hello', bytes(5)Immutable byte sequence
bytearraybytearray(b'hi')Mutable byte sequence
NoneTypeNoneSingleton
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
frozensetfrozenset({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

OperatorMeaningExample
+Addition3 + 2 → 5
-Subtraction3 - 2 → 1
*Multiplication3 * 2 → 6
/True division (always float)7 / 2 → 3.5
//Floor division7 // 2 → 3
%Modulo7 % 2 → 1
**Exponentiation2 ** 8 → 256
-xUnary negation-(-3) → 3
abs(x)Absolute valueabs(-5) → 5
divmod(a, b)(quotient, remainder)divmod(7, 2) → (3, 1)

Note: -10 % 3 is 2 in Python (result always has sign of divisor). 7 // -2 is -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)

FunctionDescriptionExample
print(*args, sep, end, file)Output to stdoutprint("a", "b", sep="-")
input(prompt)Read line from stdininput("Name: ") → str
len(obj)Length / sizelen([1,2,3]) → 3
type(obj)Type of objecttype(42) → <class 'int'>
isinstance(obj, cls)Type check (preferred)isinstance(1, int) → True
issubclass(cls, base)Subclass checkissubclass(bool, int) → True
id(obj)Memory address as intid(x)
hash(obj)Hash valuehash("abc")
dir(obj)List attributes/methodsdir([])
help(obj)Interactive helphelp(str.split)
repr(obj)Unambiguous stringrepr("hi") → "'hi'"
vars(obj)__dict__ of objectvars(instance)
callable(obj)Is it callable?callable(print) → True
getattr(obj, name, default)Get attribute by namegetattr(x, "y", None)
setattr(obj, name, val)Set attribute by namesetattr(x, "y", 5)
hasattr(obj, name)Has attribute?hasattr(x, "__len__")
delattr(obj, name)Delete attributedelattr(x, "y")
eval(expr)Evaluate expression stringeval("1+2") → 3
exec(code)Execute code stringexec("x=1")
compile(src, ...)Compile to code objectadvanced

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)

ScopeMeaning
LocalInside the current function
EnclosingIn enclosing function (closures)
GlobalModule-level names
Built-inPython 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"

Comments and Docstrings

# Single-line comment — from # to end of line

"""
Module-level docstring.
Conventionally triple-quoted, placed at very top.
"""

def foo(x):
    """Return x squared.

    Args:
        x: A number.

    Returns:
        x raised to the power 2.
    """
    return x ** 2

# Access docstrings
print(foo.__doc__)
help(foo)

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