Docsity

Python Logic Cheat Sheet | Control Flow & Algorithms, Exams of Programming Languages

Toggle sidebar
bg1
๐ŸPython Logic Cheat Sheet
1. Control Flow Logic
Concept
Syntax
Logic Pattern
If / Elif / Else
if x > 0:
elif x == 0:
else:
Evaluate conditions top-to-bottom; first
match wins
Ternary
result = "yes" if cond
else "no"
Inline decision for simple assignments
Match
(3.10+)
match value:
case 1:
...
case _:
...
Pattern matching; _= default/wildcard
Truthiness
if items: (empty list =
False)
Falsy: None,False,0,"",[],{},()
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")
pf3
pf4
pf5

Partial preview of the text

Download Python Logic Cheat Sheet | Control Flow & Algorithms and more Exams Programming Languages in PDF only on Docsity!

๐Ÿ Python Logic Cheat Sheet

1. Control Flow Logic

Concept Syntax Logic Pattern

If / Elif / Else

if x > 0: elif x == 0: else:

Evaluate conditions top-to-bottom; first

match wins

Ternary

result = "yes" if cond else "no"

Inline decision for simple assignments

Match

match value: case 1: ... case _: ...

Pattern matching; _ = default/wildcard

Truthiness

if items: (empty list =

False)

Falsy: None, False, 0 , "", [], {}, ()

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

list

Ordered, mutable,

duplicates OK

append(), pop(), sort() โ€” O(1) access

by index

tuple

Immutable record / fixed

group

Unpacking: x, y = point

dict Keyโ†’value lookup

d.get(k, default), d.items() โ€” O(1)

lookup

set

Uniqueness / membership

test

in check O(1), | union, &

intersection

risky() except (ValueError, KeyError) as e: # catch specific, not bare log(e) except Exception as e: # last resort raise RuntimeError("context") from e else:

runs if NO exception

celebrate() finally: cleanup() # always runs

Logic rule: Catch the narrowest exception that you can actually handle.

Never swallow errors silently.

6. Common Algorithm Patterns

python

Accumulator pattern

total = 0 for x in nums: total += x

Filter-map-reduce

result = sum(x**2 for x in nums if x > 0)

Two-pointer (sorted list)

l, r = 0, len(arr)- while l < r: if arr[l] + arr[r] == target: break elif arr[l] + arr[r] < target: l += 1 else: r -= 1

Frequency count

from collections import Counter freq = Counter(items).most_common(3)

Guard clauses โ€” flatten nested ifs

def process(x): if x is None: return None # exit early if x < 0: raise ValueError

return x * 2 # main path unindented

7. Complexity Quick Reference

Operation List Dict/Set

Access by index/key O(1) O(1)

Search (in) O(n) O(1)

Insert (end) O(1) amortized O(1)

Delete O(n) O(1)