The whole philosophy: Donβt ask βwhat syntax do I need?β Ask βwhat problem am I solving, whatβs the input, whatβs the output, what are the steps?β Syntax is the last 10%. This doc is built from maps, analogies, memory cards, cheat sheets, decision trees, and active recall β not a function list.
PYTHON
β
ββββββββββββββββββββββββΌβββββββββββββββββββββββ
β β β
THINK STORE ACT
β β β
Variables Lists Functions
Conditions Dictionaries Modules
Loops Sets Classes
Logic Tuples APIs
ββββββββββββββββ¬ββββββββ΄βββββββββββββββββββββββ
β
DATA βββΊ Files Β· APIs Β· Databases
β
PROCESS βββΊ Pandas / NumPy
β
ANALYZE ββΊ AUTOMATE ββΊ TEST ββΊ DEPLOY ββΊ MONITOR
Recall rule: if you can redraw this from memory, you can rebuild most of Python.
PROBLEM ββΊ UNDERSTAND ββΊ BREAK INTO SMALL STEPS ββΊ WRITE LOGIC ββΊ CODE
ββΊ RUN ββΊ CHECK RESULT ββΊ DEBUG ββΊ TEST ββΊ IMPROVE
Memory: Understand β Break β Code β Test β Improve.
INPUT ββΊ PROCESS ββΊ OUTPUT
sales = [100, 200, 300] # INPUT
total = sum(sales) # PROCESS
print(total) # OUTPUT -> 600
The computer is a juicer: fruit in, squeeze, juice out. It never guesses β you describe exact steps.
Each card draws on this shape β WHAT Β· WHY Β· PICTURE Β· TINY CODE Β· MEMORY Β· WATCH OUT β condensed to what matters most for that concept.
WHAT a name pointing to a value Β· WHY remember/reuse data Β· CODE price = 100
MEM Variable = a label stuck on data Β· WATCH '=' means assign, not "equals"
name="Ravi"; age=30; salary=50000.5; active=True
cities=["Pune","Mumbai"]; cust={"name":"Ravi","age":30}
Convert: int() float() str(). Check: type(x).
"Ravi".upper(); f"Ravi is {age} years old."; " hi ".strip(); "a,b".split(",")
MEM: f-string = drop values into text. WATCH: strip() for dirty data.
+ - * / //(floor) %(remainder) **(power) Β· WATCH: / gives float; guard divide-by-zero.
== != > < >= <= β True/False. WATCH: == compares; = assigns.
if sales > 100000: cat="High"
elif sales > 50000: cat="Medium"
else: cat="Low"
WATCH: indentation (4 spaces) defines what's "inside".
and (both) Β· or (either) Β· not (flip).
a=[10,20,30]; a.append(40); a[0]; a[-1]; a[1:3]; a.sort()
point=(19.99,73.78) # can't be changed; usable as a dict key
list(set(x)) dedupes; x in myset is super fast.
c={"name":"Ravi","age":30}
c["name"]; c.get("phone","NA"); c["phone"]="999"
for k,v in c.items(): ...
Itβs JSON, API responses, config, one row of data. WATCH: c["missing"] crashes; c.get() is safe.
ordered + changeable β LIST Β· fixed β TUPLE Β· unique β SET Β· keyβvalue β DICT
for customer in customers: process(customer)
while not done: step()
WATCH: a while loop must change its condition. break=stop, continue=skip.
def calculate_profit(revenue, cost):
return revenue - cost
Ask: what input? what output? can I test it alone? can I reuse it?
def good(p,q): return p*q # gives back the number
x = good(100,5) * 2 # works
WATCH (critical): print() SHOWS and returns None; return SENDS a value other code can use.
GLOBAL visible everywhere Β· LOCAL only inside a function. Prefer passing in / returning out.
squares=[x*x for x in nums]
big=[o for o in orders if o>10000]
MEM: a loop folded onto one line. Keep it readable.
class Customer:
def __init__(self, name): self.name = name # constructor
def shout(self): return self.name.upper()
c = Customer("Ravi"); c.shout() # 'RAVI'
DECISION: class when state + behavior belong together; plain transform β a function.
try: amount=float(row["amount"])
except ValueError: amount=None; log.warning("bad amount")
WATCH: never bare 'except: pass' β it hides real bugs.
from utils import calculate_profit Β· module = .py file, package = folder of modules.
python -m venv .venv; source .venv/bin/activate; pip install -r requirements.txt
MEM: a venv = a clean room per project, so versions never fight.
def read_big(path):
with open(path) as f:
for line in f: yield line # hand one out, pause, resume
Perfect for files too big for RAM.
with open("sales.txt") as f: data=f.read() # 'with' auto-closes safely
import csv, json
# csv.DictReader(f) -> each row a dict; json.loads/dumps; pandas.read_excel (needs openpyxl)
JSON object {} β Python dict; JSON array [] β Python list.
import pandas as pd
df = pd.read_csv("sales.csv")
df[(df["units"]>0) & (df["region"]=="West")] # filter (use &, not 'and')
df["revenue"] = df["units"] * df["unit_price"] # new column (vectorized)
df.groupby("region")["revenue"].sum() # aggregate
pd.merge(sales, customers, on="customer_id", how="left") # join
df["units"].fillna(0); df.drop_duplicates("order_id")
WATCH: pandas works in memory on ONE machine β huge data needs a DB/Spark.
SELECT cols β df[["a","b"]] WHERE β df[df.x>5] GROUP BY β df.groupby("x")
JOIN β pd.merge(a,b,on=,how=) ORDER BY β df.sort_values("x") DISTINCT β df.drop_duplicates()
np.array([1,2,3]) * 2 β vectorized fast math. pandas is built on NumPy.
import requests
r = requests.get(url, params={...}, headers={"Authorization":f"Bearer {key}"}, timeout=10)
r.raise_for_status(); data = r.json()
GET=read POST=create PUT/PATCH=update DELETE=remove Β· 200 okΒ·400 badΒ·401 unauthΒ·404 missingΒ·429 rateΒ·500 server
WATCH: always set a timeout; handle failures; retry with backoff; respect rate limits.
import sqlite3, pandas as pd
with sqlite3.connect("sales.db") as conn:
df.to_sql("sales", conn, if_exists="replace", index=False)
top = pd.read_sql_query("SELECT customer_id, SUM(revenue) r FROM sales GROUP BY customer_id ORDER BY r DESC LIMIT ?", conn, params=(3,))
WATCH (security): use parameters (?), never f-string values into SQL β SQL injection.
from pathlib import Path; import shutil
for csv in Path("data").glob("*.csv"):
...
shutil.move(str(csv), f"archive/{csv.name}")
DEBUG < INFO < WARNING < ERROR < CRITICAL
import logging; logging.basicConfig(level=logging.INFO)
log=logging.getLogger("job"); log.info("started"); log.error("file missing")
MEM: print is for learning; logging is for production.
import os; password=os.getenv("DB_PASSWORD") # never hardcode/commit secrets
def test_profit(): assert calculate_profit(200,120)==80
Test edges (zero, negative, empty, bad type). Run with pytest -q.
βEvery morning, automatically collect sales data, clean it, identify bad records, calculate KPIs, store the results in a database, and generate a management report.β
BUSINESS REQUEST
ββΊ EXTRACT (csv/excel/api/db)
ββΊ VALIDATE + CLEAN (nulls, dupes, bad dates, negative sales, bad types)
ββΊ TRANSFORM (revenue, cost, profit, margin, AOV, by customer/region/product/month)
ββΊ BUSINESS RULES (profit<0βLOSS Β· margin>30%βHIGH_MARGIN Β· sales>targetβMET)
ββΊ LOAD (SQLite) ββΊ QUERY BACK ββΊ REPORT ββΊ EMAIL ββΊ LOG every step ββΊ handle every failure
Production-readiness checklist: error handling Β· logging Β· config Β· secrets via env Β· tests Β· docs/README Β· reusable functions Β· clean structure Β· requirements.txt Β· performance aware Β· parameterized SQL Β· monitoring/log trail.
Is it actually slow? ββΊ MEASURE ββΊ find bottleneck ββΊ optimize ββΊ MEASURE again
set lookup β instant vs scanning a list Β· avoid needless loops Β· vectorize in pandas Β· generators for big streams Β· push work to the database Β· profile before guessing.
I/O-bound (many API/file waits) β threads/async. CPU-bound (heavy math) β multiprocessing.
sales_automation/
β src/ main.py extract.py transform.py load.py utils.py
β tests/ Β· config/ Β· data/ Β· logs/
β requirements.txt README.md .gitignore
add/commit β branch β PR β review β merge (never commit secrets). Deploy shapes: scheduled job (cron/Airflow/Databricks Job), server, container, cloud function. Docker = code+deps+env β one container that runs the same everywhere.
SOURCES ββΊ PYTHON ββΊ SQL ββΊ DATA PLATFORM ββΊ BI (Power BI)
Python = glue/logic/automation/APIs Β· SQL = set-based Β· Pandas = local/moderate Β· PySpark/Databricks = big distributed
store many ordered/changeable β LIST Β· unique β SET Β· fixed β TUPLE Β· keyβvalue β DICT
repeat β FOR/WHILE Β· decide β IF Β· reuse logic β FUNCTION Β· tables β PANDAS
talk to a system β API Β· read a file β FILE/PANDAS Β· records β DATABASE+SQL
might fail β TRY/EXCEPT Β· run on a schedule β SCRIPT+SCHEDULER Β· huge data β DB/SPARK
BUSINESS QUESTION ββΊ INPUT? ββΊ OUTPUT? ββΊ STEPS? ββΊ DATA STRUCTURES? ββΊ FUNCTIONS?
ββΊ EXTERNAL SYSTEMS? ββΊ WHAT CAN FAIL? ββΊ HOW TO TEST? ββΊ HOW TO DEPLOY?
1 What problem? 2 Input? 3 Output? 4 Split into functions? 5 Which data structure? 6 What can go wrong? 7 How to test? 8 Once or repeatedly? 9 Maintained by someone? 10 How runs in production?
BUG β ERROR (read message) / WRONG RESULT (check logic) β ISOLATE β FIX β TEST β PREVENT
Read a traceback bottom-up: last line = what broke; lines above = where.
VARIABLE store Β· IF decide Β· FOR each Β· WHILE repeat Β· LIST ordered Β· TUPLE fixed
SET unique Β· DICT keyβvalue Β· FUNCTION reusable Β· RETURN give back Β· CLASS blueprint
TRY/EXCEPT handle errors Β· MODULE reusable file Β· PANDAS tables Β· API programβprogram
JSON structured Β· LOGGING app diary Β· TEST verify Β· ENV clean room Β· GENERATOR one-at-a-time
=assign Β· ==compare Β· isβonly for None Β· &,| in pandas (not and/or)
PYTHON ββΊ PROBLEM ββΊ INPUT ββΊ DATA STRUCTURES ββΊ CONDITIONS ββΊ LOOPS ββΊ FUNCTIONS
ββΊ FILES/APIs/DATABASES ββΊ PANDAS ββΊ ANALYSIS ββΊ AUTOMATION ββΊ ERROR HANDLING
ββΊ TESTING ββΊ LOGGING ββΊ PROJECT STRUCTURE ββΊ DEPLOYMENT ββΊ PRODUCTION
Youβre ready not when you can define βlist,β but when handed an unfamiliar requirement you independently: understand it β define input/output β break into steps β choose data structures β write functions β read data β transform β connect API/DB β handle errors β log β test β debug β optimize β package β deploy β monitor. That reflex β think in Python β is the whole point. π