Python Cheatsheet
Control Flow
Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
if / elif / else
if x > 0: print("positive") elif x == 0: print("zero") else: print("negative") # One-liner (ternary / conditional expression) value = "yes" if condition else "no" # Nested ternary (readable only when very simple) label = "high" if x > 100 else "mid" if x > 50 else "low"
for Loop
Iterates over any iterable.
for item in [1, 2, 3]: print(item) # String characters for ch in "hello": print(ch) # Range for i in range(5): # 0 1 2 3 4 pass for i in range(2, 8): # 2 3 4 5 6 7 pass for i in range(0, 10, 2): # 0 2 4 6 8 pass for i in range(10, 0, -1): # 10 9 8 ... 1 (countdown) pass # Enumerate — index + value for i, val in enumerate(lst): print(i, val) for i, val in enumerate(lst, start=1): # 1-based index print(i, val) # Zip — parallel iteration for a, b in zip(list1, list2): pass for a, b, c in zip(l1, l2, l3): pass # zip stops at shortest; use zip_longest for full coverage: from itertools import zip_longest for a, b in zip_longest(l1, l2, fillvalue=0): pass # Unpack tuples pairs = [(1, "a"), (2, "b")] for num, letter in pairs: print(num, letter) # Dict iteration for key in d: # keys (default) pass for val in d.values(): # values pass for key, val in d.items(): # key-value pairs pass
while Loop
while condition: do_something() # Infinite loop with break while True: data = get_data() if not data: break process(data) # Common pattern: index-based i = 0 while i < len(lst): print(lst[i]) i += 1
break, continue, pass
for i in range(10): if i == 3: continue # skip to next iteration if i == 7: break # exit loop immediately print(i) # pass — syntactic no-op placeholder if condition: pass # do nothing (keeps block valid) class Empty: pass def stub(): pass
for / while … else
The else block runs if the loop completed without a break.
for item in collection: if item == target: print("found") break else: print("not found") # runs only if loop exhausted without break # Same for while while queue: item = queue.pop() if done(item): break else: print("queue exhausted")
match / case (Structural Pattern Matching, Python 3.10+)
match command: case "quit": quit() case "go" | "move": move() case _: # wildcard / default print("unknown") # Match with capture match point: case (0, 0): print("origin") case (x, 0): print(f"x-axis at {x}") case (0, y): print(f"y-axis at {y}") case (x, y): print(f"point at {x}, {y}") # Match dataclass / object attributes from dataclasses import dataclass @dataclass class Point: x: int y: int match shape: case Point(x=0, y=0): print("origin") case Point(x=x, y=y): print(f"{x}, {y}") # Guards (if clause inside case) match value: case n if n < 0: print("negative") case n if n == 0: print("zero") case n: print("positive") # Sequence patterns match lst: case []: print("empty") case [x]: print(f"single: {x}") case [first, *rest]: print(f"head={first}, tail={rest}") # Mapping patterns match d: case {"action": "buy", "item": item}: buy(item) case {"action": "sell", "item": item}: sell(item)
Exception Handling (try / except)
try: result = 10 / x except ZeroDivisionError: result = 0 except (TypeError, ValueError) as e: print(f"error: {e}") result = None except Exception as e: raise # re-raise else: print("no exception occurred") # runs only if no exception finally: cleanup() # always runs
See the Exceptions cheatsheet for full coverage of raise, exception hierarchy, and custom exceptions.
Context Managers (with)
with open("file.txt") as f: data = f.read() # Multiple context managers with open("in.txt") as fin, open("out.txt", "w") as fout: fout.write(fin.read()) # Parenthesized (Python 3.10+) with ( open("in.txt") as fin, open("out.txt", "w") as fout, ): fout.write(fin.read())
Itertools for Control Flow
from itertools import islice, takewhile, dropwhile, chain # Take first n items from any iterable list(islice(iterable, 5)) # Take items while condition holds list(takewhile(lambda x: x < 5, [1, 3, 5, 7])) # [1, 3] # Drop items while condition holds, then yield rest list(dropwhile(lambda x: x < 5, [1, 3, 5, 7])) # [5, 7] # Chain multiple iterables for item in chain([1, 2], [3, 4], [5]): print(item)
Comprehension-Based Control
# Filter equivalent evens = [x for x in range(20) if x % 2 == 0] # any / all — short-circuit over iterables any(x > 0 for x in lst) # True if at least one positive all(x > 0 for x in lst) # True if all positive # next with default — first match first = next((x for x in lst if x > 5), None)