Topic 5 of 58
Primitive Types
Overview
Primitive types are the fundamental building blocks of data in Python. The core primitives are Integers (int), Floating-point numbers (float), Strings (str), Booleans (bool), and the special NoneType. Unlike languages with strict memory limits (like a 32-bit integer in C), Python dynamically manages memory. This means a Python int can be infinitely large, restricted only by the physical RAM of your machine.
Syntax
python
# Integers (Arbitrary precision)
user_id = 49281
massive_num = 99999999999999999999999999999999999
# Floats (Decimal numbers)
pi = 3.14159
scientific = 2.5e3 # 2.5 * 10^3 = 2500.0
# Booleans (Must be capitalized)
is_active = True
has_errors = False
# NoneType (Represents absence of value, similar to null)
current_user = NoneCommon Pitfalls
- Floating-point precision errors. Because of how computers handle decimals in binary,
0.1 + 0.2equals0.30000000000000004. Use thedecimalmodule for financial calculations. - Using lowercase
trueorfalse. Python strictly requiresTrueandFalseto be capitalized.
Interview Questions
Q:
What is the maximum limit of an integer in Python?
A:
There is no fixed limit (unlike 32-bit or 64-bit bounds in C/Java). Python's int type seamlessly transitions to arbitrary-precision arithmetic, bounded only by available RAM.
Real-World Example
Using type() to validate input parameters defensively.
example
python
def calculate_discount(price, discount_percent):
# Ensure inputs are numeric before performing math
if type(price) not in (int, float):
raise TypeError("Price must be a number")
discount = price * (discount_percent / 100)
return price - discountCheck Your Knowledge
Test your understanding of Primitive Types with these quick questions.