Variables, Loops and Functions
What is it?
Python is a dynamically typed, high-level, garbage-collected programming language that serves as the foundation of modern machine learning and artificial intelligence.
At its core:
- Variables are human-readable references (names) bound to objects in heap memory.
- Control flow (
if,elif,else,match-case) determines the execution trajectory based on Boolean conditions and pattern matching. - Loops (
for,while) iterate over collections, numerical intervals, streaming batches, and training epochs. - Functions (
def,lambda) encapsulate computational logic, manage local parameter scopes, and accept flexible argument signatures (*args,**kwargs) to build modular ML training pipelines.
Motivating Example: An Epoch Training Loop
Every modern machine learning framework β from PyTorch to TensorFlow and JAX β expresses model training through standard Python control structures:
# A complete mini-batch training loop in pure Python logic
def train_one_epoch(model_weights, dataset, learning_rate=0.01):
epoch_loss = 0.0
num_samples = len(dataset)
for step, (features, target) in enumerate(dataset):
# Forward pass: compute prediction
prediction = sum(w * x for w, x in zip(model_weights, features))
error = prediction - target
loss = error ** 2
epoch_loss += loss
# Backward pass: gradient descent weight update
for i in range(len(model_weights)):
gradient = 2 * error * features[i]
model_weights[i] -= learning_rate * gradient
avg_loss = epoch_loss / num_samples
return model_weights, avg_lossWhy we need it
In machine learning engineering, writing inefficient or buggy Python syntax can slow down training runs by orders of magnitude or cause silent numerical errors:
- Understanding Object Identity vs Equality: Confusing
isand==causes subtle bugs when comparing tensor devices, None checks, or cached weights. - Dynamic Scope Resolution (LEGB): Misunderstanding variable scoping inside training loops leads to accidentally overwriting global hyperparameters or capturing stale loop variables.
- Flexible Function Signatures: PyTorch and Hugging Face neural layers accept arbitrary arguments (
def forward(self, *inputs, **kwargs):). Understanding unpacking is critical for reading and customizing open-source architectures. - Early Stopping & Branching: Training algorithms depend on robust control flow to detect divergence (NaN losses), decay learning rates, and save model checkpoints.
Explained in detail
1. Variables and the Python Memory Model
In compiled languages like C or Rust, a variable declaration allocates a fixed block of memory on the stack:
int x = 42; // Allocated 4 bytes on stack labeled "x"In Python, everything is an object allocated on the heap. A variable is simply a name (pointer) in a namespace referencing that heap object:
a = [1, 2, 3]
b = a # b points to the exact same list in heap memory
b.append(4)
print(a) # Output: [1, 2, 3, 4] β 'a' was modified through 'b'!Object Identity (is) vs Value Equality (==)
==checks if the values of two objects are equal by invoking the object's__eq__()method.ischecks if two variables point to the exact same memory address using theirid().
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True (identical contents)
print(list1 is list2) # False (distinct objects at different memory addresses)
# Always use 'is' when checking singletons like None
model = None
if model is None:
print("Initialize model weights first.")Think of Python variables as contact names in your phone's address book. "Mom" and "Dr. Smith" might both point to the exact same phone number (the object in memory). Changing the voicemail greeting under "Mom" updates it for "Dr. Smith" too, because there is only one physical phone.
2. Variable Scope and the LEGB Rule
When Python encounters a variable name, it searches for it in four sequential scopes:
learning_rate = 0.05 # Global scope
def train():
epoch = 1 # Enclosing scope for step()
def step():
loss = 0.42 # Local scope
print(f"Epoch {epoch}, Step Loss: {loss}, LR: {learning_rate}")
step()
train()Modifying Globals Inside Functions: If you assign to a variable inside a function (learning_rate = 0.01), Python treats it as a new local variable unless you explicitly declare global learning_rate. Modifying global state inside training functions is considered an antipattern β pass parameters explicitly as arguments instead!
3. Modern Type Annotations in Machine Learning
While Python is dynamically typed at runtime, modern production codebases (PyTorch, JAX, HuggingFace Transformers) use Type Hints from the typing module to document interfaces and catch bugs during static analysis:
from typing import List, Dict, Optional, Tuple, Callable
def compute_batch_loss(
predictions: List[float],
targets: List[float],
loss_fn: Callable[[float, float], float],
weights: Optional[List[float]] = None
) -> Tuple[float, Dict[str, float]]:
"""Calculates total loss and metric dictionary."""
total_loss = 0.0
for pred, target in zip(predictions, targets):
total_loss += loss_fn(pred, target)
metrics = {"mean_loss": total_loss / len(predictions)}
return total_loss, metrics4. Advanced Control Flow & Pattern Matching
Short-Circuit Evaluation
Python's and and or operators evaluate lazily:
A and B: IfAis false,Bis never evaluated.A or B: IfAis true,Bis never evaluated.
# Safe guard check: if weights is None, weights.shape is never called!
if weights is not None and len(weights) > 0:
print("Valid weight vector.")Structural Pattern Matching (match-case)
Introduced in Python 3.10+, match-case replaces long if-elif-else chains when dispatching model architectures or optimizer types:
def configure_optimizer(optimizer_type: str, lr: float):
match optimizer_type.lower():
case "adam":
print(f"Initializing Adam optimizer with lr={lr}")
case "sgd":
print(f"Initializing Stochastic Gradient Descent with lr={lr}")
case "rmsprop":
print(f"Initializing RMSprop with lr={lr}")
case _:
raise ValueError(f"Unknown optimizer: {optimizer_type}")5. Iteration Masterclass: for, while, and Loop Tools
for...else Construct
In Python, loops can have an else block. The else block runs only if the loop finishes naturally without encountering a break:
# Early stopping check: search for non-finite losses
losses = [0.85, 0.72, 0.63, 0.58]
for loss in losses:
if loss != loss or loss > 1000: # Check for NaN or explosion
print("Training diverged! Aborting.")
break
else:
print("All epochs completed successfully with stable loss.")Essential Loop Built-ins
enumerate(iterable, start=0): Returns(index, item)pairs without manual counter variables:πPythonfor batch_idx, batch in enumerate(data_loader, start=1): print(f"Batch {batch_idx}")zip(*iterables, strict=False): Pairs corresponding elements from multiple iterables:πPythonfeatures = ["age", "income", "credit_score"] importances = [0.15, 0.60, 0.25] for feat, imp in zip(features, importances, strict=True): print(f"{feat}: {imp * 100:.1f}%")reversed(sequence): Iterates over a sequence backwards in auxiliary memory without creating a reversed copy.
6. Functions in Depth: Signatures, Default Traps & Decorators
Positional-Only (/) and Keyword-Only (*) Parameters
Modern Python lets you enforce how callers provide arguments:
def train_step(data, target, /, model_name, *, learning_rate=0.01, clip_norm=1.0):
"""
- data, target: Positional-only (cannot pass data=...)
- model_name: Positional or keyword
- learning_rate, clip_norm: Keyword-only (must pass by name)
"""
pass
# train_step(X, y, "Transformer", learning_rate=0.001) # Valid!
# train_step(X, y, "Transformer", 0.001) # TypeError!The Mutable Default Argument Pitfall
Default argument values are evaluated once when the function is defined, not each time it is called:
# DANGEROUS: The list is shared across all function calls!
def record_loss(loss, history=[]):
history.append(loss)
return history
print(record_loss(0.5)) # [0.5]
print(record_loss(0.3)) # [0.5, 0.3] β Unintended state retention!
# CORRECT: Use None as default and instantiate inside the function
def record_loss_safe(loss, history=None):
if history is None:
history = []
history.append(loss)
return historyHigher-Order Functions and Decorators
Functions in Python are first-class citizens: they can be passed as arguments, assigned to variables, and returned from other functions. A decorator wraps a function to extend its behavior without modifying its source code:
import time
import functools
def benchmark(func):
"""Measures model inference or function execution time."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"[{func.__name__}] Executed in {elapsed * 1000:.2f} ms")
return result
return wrapper
@benchmark
def evaluate_model(predictions, ground_truth):
time.sleep(0.05) # Simulate metric calculation
return sum(p == g for p, g in zip(predictions, ground_truth)) / len(predictions)
acc = evaluate_model([1, 0, 1], [1, 0, 0])Quiz
π§©
Ready to test yourself?
4 questions Β· explanations shown after
Teach & Solidify
Teach This: Variables, Loops and Functions
Core Intuition
Python variables are heap object pointers resolved via the LEGB hierarchy; functions encapsulate logic with explicit scopes, default argument safety, and higher-order decorator wrapping.
Key Concepts to Explain
- 1Variables are pointers: modifying a mutable object affects every variable referencing that same memory address.
- 2Always use `None` as the default for optional mutable parameters: `def func(history=None): if history is None: history = []`.
- 3Use `strict=True` in `zip(a, b, strict=True)` to prevent silent truncation when processing mismatched feature and label lists.
- 4Decorators wrap function calls cleanly using `@functools.wraps` to preserve function docstrings and introspective metadata.
β οΈ What Most Students Get Confused About
Assuming `is` and `==` are the same for small integers vs large integers or lists. Python interns small integers (-5 to 256), but for arbitrary objects, never use `is` to check numerical value equality!
Explain Variables, Loops and Functions in your own words
Imagine you are explaining this idea to a friend or classmate with no math background. Writing it out forces your brain to bridge gaps in your intuition.
Resources & GitHub
Resources & Study Materials
Deepen your understanding with author-prepared study notes, derivation proofs, and curated educational lectures.
Official language reference covering argument unpacking, decorators, and generator mechanics.
Luciano Ramalho's definitive guide to Python data models, closures, scopes, and first-class functions.
Interactive Jupyter notebook and Python script located in this topic's resources directory.
Mastered this concept?
Tick this box when you feel confident explaining it.
Topic Resources
Python_Functions_and_Scopes_Reference.py
Python Script526 B Β· Modified Latest
Python_Variables_Loops_and_Functions_Guide.ipynb
Jupyter Notebook138.5 KB Β· Modified Latest
Was this clear?