Primitive types: int, float, bool, str
Overview
Primitive types represent the foundational data structures in Python. Think of them as the elemental building blocks—like bricks, steel, and glass—used to construct complex architectural software systems. - `int`: Integers for whole numbers. - `float`: Floats for decimals. - `bool`: Booleans for truth values. - `str`: Strings for text. Strings are immutable, meaning they cannot be modified in-place. Attempting to change a character directly will crash your program. name = "Alice" name[0] = "M" # Raises TypeError This strict immutability ensures safety when passing strings across functions. It is covered fully in `mutable-vs-immutable`. Additionally, `float` types harbor subtle precision edge cases. They cannot represent all decimal fractions perfectly. total = 0.1 + 0.2 print(total == 0.3) # False print(total) # 0.30000000000000004 This trap causes financial calculations to drift unpredictably.
Understanding these primitives is critical because every complex data structure or conditional logic ultimately evaluates down to these basic forms. Misunderstanding their boundaries, such as `float` precision or `str` immutability, introduces subtle, hard-to-trace bugs in production systems.
Where used: FastAPI, Pydantic, SQLAlchemy
Why learn this
- Defining strict type hints for `Pydantic` models in API request validation
- Writing safe state checks and numerical calculations in backend business logic
Code walkthrough
total = 0.1 + 0.2
print(total)
print(total == 0.3)
name = "User_"
count = 12
print(name + str(count))
Focus: Watch `0.1 + 0.2` land on `0.30000000000000004`, and why the `int` needs `str()` to concatenate.
Common mistakes
- Floating Point Precision: Floats cannot exactly represent all decimal fractions natively, making `0.1 + 0.2 == 0.3` evaluate to `False`. Fix: Use the standard library `decimal` module for currency or high-precision math.
- Implicit String Concatenation Fails: Attempting to add a `str` and an `int` (e.g., `'User_' + 12`) throws a `TypeError` instead of casting automatically. Fix: Explicitly cast using `str()` or leverage f-strings like `f'User_{12}'`.
Glossary
- immutability
- The characteristic of an object whose state or data cannot be changed after it is created. Example: `name = 'Alice'`.
- cast
- To explicitly convert a value from one data type to another, like changing the `int` `12` into the `str` `'12'`. Example: `str(12)`.
Recall questions
- What are the four primary primitive data types in Python?
- Why is it dangerous to use the `float` type for financial transaction calculations?
- What happens if you try to combine a `str` and an `int` using the `+` operator without casting?
- Why will `name[0] = 'M'` crash if `name` is a `str`?
Understanding checks
What happens when this script is run?
A TypeError is raised.
Python does not implicitly coerce an `int` into a `str` during concatenation. You must explicitly cast the integer using `str(amount)` or use formatted string literals (f-strings) like `f'The total is: {amount}'`.
A developer wrote this code to calculate exact currency values. Identify the conceptual bug.
Using `float` types for precise monetary calculations.
Because floats cannot exactly represent all decimal fractions, `0.1 + 0.2` evaluates to `0.30000000000000004`, causing the `== 0.3` check to fail. For financial calculations requiring exact precision, you should use the `decimal` module instead of `float`.
Practice tasks
Fix the API Response Formatter
The function below currently returns a basic `str`, but it crashes if `balance` is appended directly and it ignores the other parameters. Modify it to return an f-string: if active, return `'Active user {username} (Age: {age}) has ${balance:.2f}'`. If inactive, replace `'Active'` with `'Inactive'`.
Challenge
E-commerce Discount Calculator
Create a function `calculate_final_price` simulating an e-commerce checkout. It receives a `base_price` (`float`) and an `is_discount_valid` status (`bool`). If the code is valid, apply a 15% discount. Ensure the final price is returned as a formatted `str` representing currency: `'Total: $'`.
Continue learning
Next: Dynamic typing and type()