Python Survival • Side A: Syntax

Variables • Logic • Loops • Data
1. Variables & Casting
x = 5 # int y = 3.14 # float name = "Dave" # str ok = True # bool
Casting (Fix TypeErrors):
int("5") # 5 | str(5) # "5" float(5) # 5.0 | bool(0) # False
2. Math (BEDMAS)
**Exponent (Power)1st
* / // %Mult, Div, Floor, Mod2nd
+ -Add, Sub3rd
10 // 3 # 3 (Floor Div) 10 % 3 # 1 (Remainder) x += 1 # Increment
3. Logic & Control
if x > 10: print("Big") elif x == 10: print("Exact") else: print("Small")
== Equal!= Not Eq
and Both Trueor Any True
not Flip T/Fin Exists?
4. Loops (Repetition)
While Loop:
c = 0 while c < 5: print(c) c += 1 # Update!
For Loop (Range):
# 0 to 4 for i in range(5): ... # 2, 4, 6, 8 (Stop=10 excl) for i in range(2, 10, 2): ... # 5, 4, 3, 2, 1 (Reverse) for i in range(5, 0, -1): ...
5. Functions
def add(a, b): res = a + b return res # Sends back x = add(5, 2) # x becomes 7
⚠️ Vars inside functions are LOCAL (invisible outside).
6. Strings (Immutable)
s = " Code " s[0] # ' ' (Index 0) s[-1] # ' ' (Last) s[1:5] # 'Code' (Slice) len(s) # 6
.strip()Kill whitespace
.lower()" code "
.upper()" CODE "
.replace("o","a")" Cade "
.find("d")Index (3)
msg = f"Val: {x}" # F-String
7. Lists (Mutable [])
L = [10, 20, 30] L[0] = 99 # [99, 20, 30] L.append(40) # Add to end
.pop(i)Remove at index
.remove(v)Remove value
.insert(i,v)Add at index
.sort()Order A-Z
v in LCheck exists
8. Dictionaries (Key:Val)
d = {"name": "Jo", "age": 20} val = d["name"] # "Jo" d["city"] = "NY" # Add safe = d.get("id", 0) # No crash
Looping:
for k, v in d.items(): print(k, v)
9. Files (Read/Write)
with open("file.txt", "r") as f: lines = f.readlines() for line in lines: print(line.strip())

"w"=Overwrite, "a"=Append

10. Error Handling
try: x = 10 / 0 except ZeroDivisionError: print("Bad Math") except ValueError: print("Bad Type")
Generated for Confident Apathy Strategy - Page 1

Python Survival • Side B: Recipes

Algorithms • Patterns • Models
Algorithm: Accumulator (Sum/Count)

Goal: Add up numbers or count items.

total = 0 # 1. Initialize count = 0 nums = [10, 20, 5, 40] for n in nums: # 2. Loop total += n # 3. Accumulate count += 1 # 3. Count print(f"Avg: {total/count}")
Algorithm: Find Max/Min

Goal: Find largest item without max().

nums = [5, 2, 9, 1] highest = nums[0] # Assume 1st is max for n in nums: if n > highest: # Found new max? highest = n # Update it print(highest) # 9
Algorithm: Safe Input Loop

Goal: Force user to give valid integer.

while True: val = input("Enter 1-10: ") # 1. Check if digits if val.isdecimal(): num = int(val) # 2. Check Range if 1 <= num <= 10: print("Valid!") break # Exit loop else: print("Out of range") else: print("Not a number")
Algorithm: Filter List

Goal: Copy only even numbers to new list.

old = [1, 2, 3, 4] new_list = [] for n in old: if n % 2 == 0: # Check even new_list.append(n) print(new_list) # [2, 4]
Reference: The Hierarchy

When in doubt, use Parentheses.

OrderOperatorDesc
1. KING( )Parentheses
2. Power**Exponents
3. Sign-x, +xPositive/Neg
4. Math* / // %Mult/Div
5. Math+ -Add/Sub
6. Compare== > <Relational
7. LogicnotLogical Not
8. LogicandLogical And
9. LogicorLogical Or
Design: Flowcharts & IPO
Flowchart Symbols:
🟢 Oval
Start / End
▱ Parallelogram
Input / Output
▭ Rectangle
Process / Calc
◇ Diamond
Decision (If)
IPO Model:

Input: User data (params)
Process: The logic/math
Output: The result (return/print)

Useful Built-in Functions
abs(-5)5 (Positive)
round(3.6)4 (Nearest)
round(3.14, 1)3.1 (1 decimal)
max(1, 2)2 (Largest)
min(1, 2)1 (Smallest)
len(obj)Length
type(x)Check Type
Module: Random
import random # Random Int (Inclusive) x = random.randint(1, 10) # Random Float (0.0 - 1.0) y = random.random()
"I can fail math and still pass."
- Famous Last Words, 2025
Generated for Confident Apathy Strategy - Page 2