← Master Index
Vol. 03 Module 3.1 Lecture

Data Types

Python Basics

How This Lesson Fits the Module

In Variables, you learned that names point to objects. Data types classify those objects: a learning rate is a float, an epoch count is an int, a model path is a str, and a “training complete” flag is a bool.

AI pipelines mix types constantly—reading CSV strings, casting to floats for normalization, comparing metrics with booleans for early stopping. Choosing and converting types correctly prevents silent bugs that derail experiments.

Learning Objectives

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

  • Identify Python’s core built-in types: int, float, str, bool, and NoneType.
  • Explain why floats and integers behave differently in arithmetic and indexing.
  • Convert between types using int(), float(), and str() safely.
  • Distinguish mutable collection types (preview) from immutable scalars.
  • Map ML quantities to appropriate Python types.
  • Use isinstance() to validate configuration and API responses.

Introduction: Types as Contracts

Every object in Python has a type—a class that defines what operations are valid. You cannot add a string to a float without conversion; you cannot use a float as a list index. Types are implicit contracts between parts of your code.

In Volume 02, scalars were real numbers; vectors were ordered lists. In Python, those become float scalars and list or NumPy ndarray objects—each with distinct types and capabilities.

Numeric Types: int and float

Definition — Numeric Types

int represents integers (whole numbers) with arbitrary precision in Python 3. float represents double-precision floating-point numbers approximating real values. ML hyperparameters, losses, and probabilities are typically float; counts (epochs, batch size, token length) are typically int.

ML Quantity Type Example
Epoch count int num_epochs = 50
Learning rate float learning_rate = 3e-4
Loss value float train_loss = 0.342
Class label index int label = 7
Softmax probability float confidence = 0.973
batch_size = 32 # int learning_rate = 1e-3 # float (scientific notation) # Division always returns float in Python 3 half = 7 / 2 # 3.5, not 3 floor_div = 7 // 2 # 3 — integer division # Float precision caveat print(0.1 + 0.2) # 0.30000000000000004

int

  • Exact whole numbers
  • Indexing, counting, labels
  • range() and len() results
  • No decimal component

float

  • Approximate reals
  • Loss, gradients, probabilities
  • Scientific notation: 1e-4
  • Watch precision in comparisons

Strings and Booleans

Definition — str and bool

str (string) stores text—UTF-8 Unicode characters in Python 3. bool stores truth values True or False. Strings label data and configure pipelines; booleans gate logic such as early stopping and feature flags.

model_name = "bert-base-uncased" dataset_path = "/data/train.csv" # f-strings — embed variables in logs epoch, loss = 10, 0.234 print(f"Epoch {epoch}: loss={loss:.4f}") # Booleans in training logic use_gpu = True early_stop = val_loss < best_loss is_converged = early_stop and epoch > 5

None: The Absence of Value

None is a singleton object meaning “no value yet.” Optional hyperparameters, uninitialized metrics, and missing API fields often use None before assignment.

best_val_loss = None # updated after first validation pass if best_val_loss is None: best_val_loss = current_loss elif current_loss < best_val_loss: best_val_loss = current_loss

Use is None and is not None for comparisons—never == None.

Type Conversion

Data ingestion often delivers strings from CSV or JSON. You must cast to numeric types before math.

Function Input Example Output
int("42") String digit 42
float("0.001") String decimal 0.001
int(3.9) Float 3 (truncates toward zero)
str(0.95) Float "0.95"
bool(0) Zero False
What’s Next in This ModuleThe next lecture, Operators, applies arithmetic and comparison operators to these types—the mechanics behind loss computation and metric evaluation.

Truthiness and Type Checking

Python treats many values as True or False in conditionals: zero, empty strings, and None are falsy; non-zero numbers and non-empty collections are truthy.

# Validate config from YAML/JSON config_lr = "0.001" if isinstance(config_lr, str): config_lr = float(config_lr) assert isinstance(config_lr, float) assert config_lr > 0

Common Misconceptions

Misconception 1:1 and 1.0 are the same type.”

Why people believe it: They print similarly and compare equal with ==.

Reality: type(1) is int; type(1.0) is float. Some libraries expect strict types; indexing requires int, not float.

Misconception 2: “Floats are exact like math reals.”

Why people believe it: Console output rounds display.

Reality: IEEE 754 floats are approximations. Use tolerance checks (abs(a - b) < 1e-6) instead of a == b for loss comparisons.

Misconception 3:bool is unrelated to int.”

Why people believe it: They are taught as separate concepts.

Reality: bool is a subclass of int; True == 1 and False == 0. Prefer explicit booleans in ML logic for clarity.

Quick Knowledge Check

  1. Short Answer: What type holds 0.001? Answer: float.
  2. True/False: 7 / 2 equals 3 in Python 3. Answer: False — result is 3.5 (float).
  3. Multiple Choice: Best type for num_classes: (a) str, (b) int, (c) bool, (d) None. Answer: (b).
  4. Short Answer: How do you convert "0.95" to a number? Answer: float("0.95").
  5. True/False: None == 0 is True. Answer: False.
  6. Short Answer: Why use is None instead of == None? Answer: Identity check; idiomatic and avoids overridden equality.
  7. Multiple Choice: Which is falsy? (a) 1, (b) "hello", (c) 0, (d) [0]. Answer: (c).
  8. True/False: f-strings can embed variable values in log messages. Answer: True.
  9. Short Answer: What type stores "gpt-4"? Answer: str.
  10. Multiple Choice: Safe way to check if a config value is a float: (a) type(x) == "float", (b) isinstance(x, float), (c) x is float, (d) float == x. Answer: (b).

Key Takeaways

  • Core scalar types: int, float, str, bool, and None.
  • Counts and indices use int; losses, rates, and probabilities use float.
  • Strings carry text labels, paths, and serialized config; booleans gate control flow.
  • Cast types explicitly when ingesting string data from files or APIs.
  • Float comparisons need tolerance; floats are approximations, not exact reals.
  • Next: Operators for arithmetic and logic on these types.
Trainer’s Guide

Hands-on idea: Load a CSV column as strings, convert to float, compute mean—mirroring Volume 02 statistics in pure Python before NumPy.

Debugging exercise: Show 0.1 + 0.2 == 0.3 returning False; introduce math.isclose().

Discussion prompt: Which fields in a model config should be int vs float vs str vs bool?

What’s Next Continue to Operators to combine and compare typed values in expressions.