1. Control Flow Logic
Concept Syntax Logic Pattern
if x > 0:
Evaluate conditions top-to-bottom; first
If / Elif / Else elif x == 0:
match wins
else:
result = "yes" if cond
Ternary Inline decision for simple assignments
else "no"
match value:
case 1:
Match
... Pattern matching; _ = default/wildcard
(3.10+)
case _:
...
if items: (empty list =
Truthiness Falsy: None, False, 0, "", [], {}, ()
False)
2. Loop Logic
python
# For loop — iterate over sequence
for item in items:
if item == target:
break # exit loop entirely
if item < 0:
continue # skip to next iteration
else:
# runs only if loop completed WITHOUT break
print("not found")
, # While loop — repeat until condition fails
while not done:
done = check()
# Enumerate — index + value
for i, val in enumerate(items, start=1):
print(i, val)
# Zip — parallel iteration
for a, b in zip(list1, list2):
print(a, b)
# Comprehension — build list in one line
squares = [x**2 for x in range(10) if x % 2 == 0]
lookup = {k: v for k, v in pairs}
unique = {x for x in items}
Logic rule: Use for when you know the sequence; use while when you know the
condition. Always ask: "Do I need the index?" → enumerate; "Do I need pairs?" → zip.
3. Data Structure Selection Logic
Structure Use When Key Operations
Ordered, mutable, duplicates append(), pop(), sort() — O(1) access by
list
OK index
Immutable record / fixed
tuple Unpacking: x, y = point
group
d.get(k, default), d.items() — O(1)
dict Key→value lookup
lookup
Uniqueness / membership
set in check O(1), | union, & intersection
test