← Master Index
Vol. 03 Module 3.1 Lecture

Variables

Python Basics

Bridge from Volume 02: Mathematics to Code

In Volume 02: Mathematics for AI, you worked with symbols—μ for mean, α for learning rate, w for weight vectors. Those symbols lived on paper and in equations. Variables are how you give those quantities names in Python so a computer can store, update, and compute with them.

The capstone lecture Gaussian / Normal Distribution previewed NumPy code: np.mean(x), np.std(x), and z-score standardization. Every value in that snippet—x, samples, z—is held in a variable. This lecture is where abstract math becomes executable engineering.

Learning Objectives

By the end of this lesson, students should be able to:

  • Define a Python variable as a name bound to an object in memory.
  • Assign values using = and reassign variables as training state changes.
  • Apply PEP 8 naming conventions for readable AI engineering code.
  • Explain dynamic typing and why the same name can hold different types across a script.
  • Inspect values and types with print(), type(), and id().
  • Map mathematical symbols from Volume 02 to meaningful Python variable names.
  • Recognize naming mistakes that cause bugs in ML pipelines.

Introduction: Names for Computational Objects

A variable is a label you attach to a value stored in the computer’s memory. When you write learning_rate = 0.001, Python creates a numeric object 0.001 and binds the name learning_rate to it. Later, when the optimizer reads learning_rate, it retrieves that value—no need to hunt through memory addresses manually.

In AI engineering, variables hold everything from hyperparameters and file paths to intermediate tensors and evaluation metrics. Clear naming is not cosmetic; it is how teammates (and future you) understand what each quantity represents in a training pipeline.

Assignment and Reassignment

Definition — Variable Assignment

Assignment in Python uses the = operator to bind a name on the left to an object on the right. Assignment does not mean mathematical equality—it means “store this object under this name.” Reassignment replaces the binding: the name now refers to a new object, while the old object may remain in memory until garbage-collected.

# Initial assignment — learning rate scalar from Vol. 02 learning_rate = 0.001 # Reassignment after schedule step learning_rate = 0.0005 # Multiple names can reference the same object batch_size = 32 effective_batch = batch_size # both names → same int object # Update training epoch counter each loop iteration epoch = 0 epoch = epoch + 1 # now epoch is 1

Notice the pattern in a training loop: epoch, loss, and learning_rate are reassigned repeatedly. The name stays stable; the value evolves—exactly like tracking “current loss” across iterations in a math derivation.

Naming Conventions for AI Engineers

Python’s official style guide, PEP 8, recommends snake_case for variables: lowercase words separated by underscores. In ML codebases, descriptive names prevent costly confusion between similarly shaped quantities.

Math Symbol (Vol. 02) Python Variable What It Holds
α (learning rate) learning_rate Scalar step size for gradient descent
ℒ (loss) train_loss, val_loss Scalar loss per split
X (feature matrix) feature_matrix or X_train 2D array of input features
μ, σ feature_mean, feature_std Normalization statistics
P(y | x) posterior_prob Conditional probability from Bayes

Good Names

  • num_epochs = 100
  • validation_accuracy = 0.94
  • embedding_dim = 768
  • Reveal role and unit where helpful

Weak Names

  • x = 100 (epochs? features?)
  • temp = 0.94 (temperature? temporary?)
  • data1, data2
  • Force readers to trace code to infer meaning

Dynamic Typing

Unlike languages such as C++ or Java, Python does not require you to declare a variable’s type in advance. The type is determined by the object currently bound to the name. This is dynamic typing—flexible for prototyping, but a source of bugs if you assume the wrong type.

Definition — Dynamic Typing

In Python, a variable name can be rebound to objects of different types at different times. The type belongs to the object, not the name. Use type(variable) to inspect what a name currently references.

metric = 0.87 print(type(metric)) # <class 'float'> metric = "epoch_42" # rebound to string — legal in Python print(type(metric)) # <class 'str'> batch_size = 32 batch_size = [16, 32, 64] # now a list of candidate batch sizes print(type(batch_size)) # <class 'list'>

In production ML code, you rarely rebind a name to a completely different type—that confuses readers. Dynamic typing shines when one function accepts both Python lists and NumPy arrays during exploration, before you standardize on tensors.

Variables vs Mathematical Symbols

On Paper (Vol. 02)

  • μ denotes population mean
  • Context defines meaning
  • Single letters save space
  • Subscripts distinguish versions: wt

In Python (Vol. 03)

  • population_mean or mu
  • Names must be self-documenting in long files
  • Descriptive snake_case preferred
  • Suffixes: weights_t, loss_prev
# Z-score from Gaussian lecture — now with named variables import numpy as np raw_scores = np.array([12.0, 15.0, 9.0, 14.0, 11.0]) feature_mean = np.mean(raw_scores) # μ feature_std = np.std(raw_scores) # σ z_scores = (raw_scores - feature_mean) / feature_std print(f"mean={feature_mean:.2f}, std={feature_std:.2f}") print(z_scores)
What’s Next in This ModuleThe next lecture, Data Types, classifies the objects variables can reference—integers, floats, strings, booleans, and the collections that hold datasets.

Inspecting Variables

Debugging ML pipelines starts with asking: what value does this name hold right now, and what type is it?

Function Purpose AI Engineering Use
print(x) Display human-readable value Log loss and metrics during training
type(x) Return object’s class Verify API returned a float, not a string
id(x) Return memory identity Check if two names share one object
isinstance(x, float) Boolean type check Validate config values before training

Common Misconceptions

Misconception 1:= means ‘equals’ in the mathematical sense.”

Why people believe it: Math classes use = for equality.

Reality: In Python, = assigns. Equality is tested with ==. Writing loss = loss + 0.01 updates the variable; it does not assert equality.

Misconception 2: “A variable is a box that contains a value.”

Why people believe it: Common textbook metaphor.

Reality: Python variables are names (references) pointing to objects. Multiple names can reference the same object; reassigning one name does not copy the object unless you explicitly do so.

Misconception 3: “Declaring types upfront is always necessary.”

Why people believe it: Experience with statically typed languages.

Reality: Python infers types at runtime. Type hints (learning_rate: float = 0.001) are optional documentation and tooling aids—covered later in this volume—not runtime requirements.

Quick Knowledge Check

  1. Short Answer: What does learning_rate = 0.01 do? Answer: Binds the name learning_rate to the float object 0.01.
  2. True/False: Python variables must be declared with a type before use. Answer: False — Python uses dynamic typing.
  3. Multiple Choice: Which naming style follows PEP 8? (a) LearningRate, (b) learning-rate, (c) learning_rate, (d) LEARNINGRATE. Answer: (c).
  4. Short Answer: How do you check the type of val_loss? Answer: type(val_loss) or isinstance(val_loss, float).
  5. True/False: After a = b, changing b always changes a. Answer: False for immutable types like int/float; True for mutable shared objects like lists.
  6. Short Answer: Map the math symbol α to a Python variable name. Answer: learning_rate (or similar descriptive name).
  7. Multiple Choice: = in Python is: (a) assignment, (b) equality test, (c) comparison, (d) type declaration. Answer: (a).
  8. True/False: Reassigning epoch = epoch + 1 is a common training-loop pattern. Answer: True.
  9. Short Answer: Why use train_loss instead of l? Answer: Readability and self-documentation in large codebases.
  10. Multiple Choice: Volume 02 math becomes runnable in Volume 03 primarily through: (a) variables, (b) comments, (c) file paths, (d) HTML. Answer: (a).

Key Takeaways

  • Variables are names bound to objects; assignment uses =, not mathematical equality.
  • Volume 02 symbols (μ, α, ℒ) become descriptive Python names like feature_mean and learning_rate.
  • Python is dynamically typed: the type belongs to the object, inspectable via type().
  • PEP 8 snake_case naming improves readability in AI engineering teams.
  • Reassignment lets you track evolving training state (epoch, loss, learning rate).
  • Next: Data Types explores what kinds of objects variables can reference.
Trainer’s Guide

Bridge activity: Display the z-score formula from Module 2.3 and have students write the Python version with named variables before running NumPy. Connect each symbol to a variable name on the board.

Hands-on idea: Give students a script with cryptic names (x, t, d) and ask them to rename variables for a mini training config without changing behavior.

Discussion prompt: When is rebinding a variable to a different type acceptable versus harmful in production ML code?

What’s Next Continue to Data Types to learn the built-in types that hold scalars, text, truth values, and the collections behind datasets.