Python Core
Scope: Python Fluency → NumPy/Pandas/Jupyter → Essential Machine Learning → scikit-learn → FastAPI Model Serving → PyTorch Tensors, Dataset/DataLoader, and Neural Networks
Use this as a quick review sheet. Focus on understanding the purpose of each concept rather than memorizing every function.
1.1 Syntax & Data Structures
Python uses indentation instead of {} for blocks.
age = 20
if age >= 18:
print("Adult")
Main data structures
# List — ordered, mutable
grades = [90, 85, 95]
# Tuple — ordered, usually treated as immutable
coordinate = (10, 20)
# Dictionary — key/value pairs
student = {
"name": "John",
"grade": 90
}
# Set — unique values
tags = {"python", "ai", "ml"}
Real-world uses - list: predictions, records, features - tuple:
fixed groups such as coordinates/shapes - dict: JSON/API data and
configuration - set: removing duplicates / membership checks
Important: Strings need quotes.
name = "John"
1.2 Functions
def calculate_average(grades: list[float]) -> float:
return sum(grades) / len(grades)
Default parameters:
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}"
Why functions matter
Functions make code: - reusable - easier to test - easier to maintain - easier to separate into modules
AI use: preprocessing, loading models, training, evaluation, prediction.
1.3 Comprehensions
Compact way to transform/filter collections.
scores = [60, 80, 90, 50]
passing = [score for score in scores if score >= 75]
Transform:
adjusted = [score + 5 for score in scores]
Pattern:
[result for item in items if condition]
Important: Prefer a normal loop when the comprehension becomes hard to read.
1.4 Modules & Packages
A module is usually one .py file.
scores.py
A package is a directory containing related modules.
utils/
├── scores.py
└── validation.py
Import:
from utils.scores import average
Real-world use: separate API routes, model code, schemas, preprocessing, utilities, etc.
1.5 Classes
class MLModel:
def __init__(self, name: str, accuracy: float):
self.name = name
self.accuracy = accuracy
def is_good(self) -> bool:
return self.accuracy >= 0.80
Create an instance:
model = MLModel("Classifier", 0.90)
JS/TS comparison
Python self ≈ JavaScript this
Python __init__ ≈ constructor
Inheritance:
class Child(Parent):
def __init__(self):
super().__init__()
1.6 Dataclasses
Useful for classes that mostly store structured data.
from dataclasses import dataclass
@dataclass
class Experiment:
name: str
accuracy: float
Python automatically provides useful methods such as initialization.
Use case: configuration, experiment metadata, structured application data.
1.7 Exceptions
Handle expected failures:
try:
value = int("123")
except ValueError:
print("Invalid number")
Raise your own:
if age < 0:
raise ValueError("Age cannot be negative")
Common exceptions:
ValueError
TypeError
KeyError
FileNotFoundError
Avoid:
except:
pass
It hides bugs.
1.8 Type Hints
def predict(text: str) -> float:
return 0.85
Collections:
def average(values: list[float]) -> float:
...
Optional value:
name: str | None = None
Important: Python type hints normally do not enforce types at runtime. They improve readability, IDE support, static checking, and framework integration.
1.9 Virtual Environments
A virtual environment isolates project dependencies.
Create:
python -m venv .venv
Activate on macOS/Linux:
source .venv/bin/activate
Install packages:
python -m pip install numpy pandas scikit-learn
Save dependencies:
python -m pip freeze > requirements.txt
.gitignore:
.venv/
__pycache__/
Important: Activating a venv does not install dependencies. It only switches which Python environment you are using.
1.10 Files & JSON
Read file:
with open("data.txt", "r") as file:
content = file.read()
JSON:
import json
with open("config.json", "r") as file:
data = json.load(file)
Write JSON:
with open("result.json", "w") as file:
json.dump(data, file)
Remember
json.load() → file → Python
json.loads() → string → Python
json.dump() → Python → file
json.dumps() → Python → string
AI use: configuration, experiment metadata, prediction results.
1.11 Async Python
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return "Done"
asyncio.run(fetch_data())
Run independent async operations together:
results = await asyncio.gather(
fetch_a(),
fetch_b()
)
Best for: I/O-bound work such as APIs, databases, network calls, and LLM requests.
Not automatically faster for: CPU-heavy model training.