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, andNoneType. - Explain why floats and integers behave differently in arithmetic and indexing.
- Convert between types using
int(),float(), andstr()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
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 |
int
- Exact whole numbers
- Indexing, counting, labels
range()andlen()results- No decimal component
float
- Approximate reals
- Loss, gradients, probabilities
- Scientific notation:
1e-4 - Watch precision in comparisons
Strings and Booleans
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.
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.
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 |
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.
Common Misconceptions
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.
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.
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
- Short Answer: What type holds
0.001? Answer: float. - True/False:
7 / 2equals3in Python 3. Answer: False — result is 3.5 (float). - Multiple Choice: Best type for
num_classes: (a) str, (b) int, (c) bool, (d) None. Answer: (b). - Short Answer: How do you convert
"0.95"to a number? Answer: float("0.95"). - True/False:
None == 0is True. Answer: False. - Short Answer: Why use
is Noneinstead of== None? Answer: Identity check; idiomatic and avoids overridden equality. - Multiple Choice: Which is falsy? (a) 1, (b) "hello", (c) 0, (d) [0]. Answer: (c).
- True/False: f-strings can embed variable values in log messages. Answer: True.
- Short Answer: What type stores
"gpt-4"? Answer: str. - 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, andNone. - Counts and indices use
int; losses, rates, and probabilities usefloat. - 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.
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?