HelloAI
L1 Chapter 7 🥚 🕒 11 min

Python Crash Course (Part 1): The Essentials for ML

You don't need to be a Python wizard for ML — you need these 30%.

A
Alai
6/15/2026

You don’t need to master Python before doing ML. You need enough Python to follow ML code and tweak it.

This piece covers that 30%.

Variables and Types

# Numbers
x = 42
pi = 3.14159
big = 1e9       # 1,000,000,000

# Strings
name = "Claude"
greeting = f"Hello, {name}!"   # f-string

# Booleans
ready = True
done = False

# None
empty = None

Python is dynamically typed — x can be assigned different types later. For ML, you’ll mostly use numbers.

Lists

nums = [1, 2, 3, 4, 5]

# Index
nums[0]      # 1
nums[-1]     # 5 (last)
nums[1:3]    # [2, 3] (slice)

# Modify
nums.append(6)
nums[0] = 99

# Iterate
for n in nums:
    print(n)

# List comprehension (THE Python idiom)
squared = [n**2 for n in nums]      # [9801, 4, 9, 16, 25, 36]
evens = [n for n in nums if n % 2 == 0]   # filter

List comprehensions are everywhere in ML code. Get used to them.

Dictionaries

person = {"name": "Alice", "age": 30}

# Access
person["name"]               # "Alice"
person.get("email", "n/a")  # safe access with default

# Modify
person["city"] = "Tokyo"

# Iterate
for key, value in person.items():
    print(f"{key}: {value}")

# Dict comprehension
squares = {n: n**2 for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

ML datasets are often dicts. ML configs are dicts. Get comfortable.

Tuples

point = (3.0, 4.0)           # immutable
x, y = point                 # unpacking

Used for: function return values, fixed-size sequences, dict keys.

Functions

def greet(name, greeting="Hello"):
    """Greet someone."""
    return f"{greeting}, {name}!"

greet("Alice")                  # "Hello, Alice!"
greet("Bob", greeting="Hi")     # "Hi, Bob!"

# Lambda (anonymous function)
square = lambda x: x**2
square(5)   # 25

# Used in sort, map, filter
nums = [3, 1, 4, 1, 5]
sorted_nums = sorted(nums, key=lambda x: -x)  # descending

Classes

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says woof!")

    def __repr__(self):
        return f"Dog({self.name}, age={self.age})"

d = Dog("Rex", 3)
d.bark()      # Rex says woof!
print(d)      # Dog(Rex, age=3)

In ML, you’ll define model classes like this — extend nn.Module in PyTorch.

Control Flow

# if / elif / else
if x > 100:
    print("big")
elif x > 10:
    print("medium")
else:
    print("small")

# for loop
for i in range(10):    # 0 to 9
    print(i)

for i, item in enumerate(["a", "b", "c"]):
    print(f"{i}: {item}")

# while
while x > 0:
    x -= 1

# Common pattern
for i in range(len(arr)):
    arr[i] *= 2
# Better:
for i, val in enumerate(arr):
    arr[i] = val * 2

Importing

import numpy as np                # standard alias
import torch.nn as nn
from sklearn.linear_model import LogisticRegression
from pathlib import Path

Almost every ML script starts with these. The shortcut aliases (np, pd, nn, plt) are conventions everyone uses.

File I/O

# Read a file
with open("data.txt") as f:
    content = f.read()

# Read line by line
with open("data.txt") as f:
    for line in f:
        print(line.strip())

# Write
with open("output.txt", "w") as f:
    f.write("Hello\n")

# JSON
import json
with open("config.json") as f:
    config = json.load(f)

with ensures the file is closed automatically. Use it always.

String Methods

s = "  Hello, World!  "
s.strip()                 # "Hello, World!"
s.lower()                 # "  hello, world!  "
s.split(",")              # ["  Hello", " World!  "]
"-".join(["a", "b", "c"]) # "a-b-c"
s.replace("World", "AI")  # "  Hello, AI!  "
s.startswith("  H")       # True
"py" in "python"          # True

Error Handling

try:
    result = 10 / x
except ZeroDivisionError:
    print("Can't divide by zero!")
except Exception as e:
    print(f"Error: {e}")
finally:
    print("Always runs")

Modules and Pip

# Install a package
pip install numpy

# In Python file
import numpy as np

The Python package ecosystem is massive. ML uses many — numpy, pandas, scikit-learn, torch, transformers, etc.

A Complete ML Script Skeleton

What a typical ML script looks like:

import torch
import torch.nn as nn
from torch.utils.data import DataLoader

# 1. Load data
data = load_data()
loader = DataLoader(data, batch_size=32)

# 2. Define model
class MyModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer = nn.Linear(100, 10)

    def forward(self, x):
        return self.layer(x)

model = MyModel()

# 3. Train
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

for epoch in range(10):
    for x, y in loader:
        pred = model(x)
        loss = criterion(pred, y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    print(f"Epoch {epoch}: loss = {loss.item():.4f}")

# 4. Evaluate / save
torch.save(model.state_dict(), "model.pt")

The patterns repeat across most ML code.

Things You Can Skip (For Now)

These are nice-to-have but not essential:

  • Async / await
  • Metaclasses
  • Decorators (you’ll use them: @property, @torch.no_grad(), but rarely write them)
  • Generators / yield
  • Type hints (good to read, not required to write)

Focus on the basics. Pick up advanced features as you encounter them.

  • Python 3.10+ (3.12 if possible)
  • VS Code + Python extension
  • Jupyter Notebook for exploration
  • Black for auto-formatting
  • Ruff for linting (super fast)

Practice Sources

  • realpython.com — quality tutorials
  • Python docs — surprisingly readable
  • Kaggle notebooks — see real ML code
💡 A pragmatic note

You don’t need to learn Python “fully” before starting ML.

Learn Python by doing ML.

Each new technique you encounter (PyTorch, transformers, fastai) will teach you a new Python pattern. 6 months of ML projects = better Python than 6 months of Python tutorials.

Get this 30% under your belt → start hacking ML code → fill gaps as you go.

Next recommended: L1-08 NumPy or L1-04 Probability.