1. Introduction to Data Types in Python
In computer science, a data type defines the classification or category of an item of data. It tells the interpreter how the developer intends to use the data, what mathematical or logical operations can be performed on it, and how much memory space it requires.
Because everything in Python is an object, data types are implemented internally as built-in classes. When you assign a value to a variable, you are instantiating an object of that specific class. You can inspect the data type of any object at runtime using the built-in type() function.
Overview Hierarchy of Python's Primary Built-in Types
Python Built-in Data Types │ ├── Numeric Types : int, float, complex ├── Boolean Type : bool (Subclass of int) ├── Text Sequence Type : str ├── Sequence Types : list, tuple, range ├── Mapping Type : dict ├── Set Types : set, frozenset ├── Binary Types : bytes, bytearray, memoryview └── Null Type : NoneType
2. Deep Dive: Core Primitive Data Types
1. Numeric Types (`int`, `float`, `complex`)
Python provides three distinct built-in numeric classes:
- Integers (`int`): Represents whole numbers (positive, negative, or zero) without decimals. Unlike languages such as C++ or Java that cap integers at 32 or 64 bits, Python integers have arbitrary precision—meaning their size is limited only by your computer's available RAM.
- Floating-Point Numbers (`float`): Represents real numbers containing a decimal point or written in exponential (scientific) notation. Floats are implemented using standard double-precision (64-bit) IEEE 754 floating-point format.
- Complex Numbers (`complex`): Represents mathematical complex numbers in the form
real + imaginary j, wherejrepresents $\sqrt{-1}$.
# Integer with arbitrary precision
large_int = 987654321012345678909876543210
print("Int Value:", large_int, "| Type:", type(large_int))
# Float with decimal and scientific notation
pi_approx = 3.14159
scientific_num = 2.5e4 # 2.5 * 10^4 = 25000.0
print("Float Value:", pi_approx, "| Type:", type(pi_approx))
print("Scientific Float:", scientific_num, "| Type:", type(scientific_num))
# Complex Number
z = 3 + 5j
print("Complex Value:", z, "| Real:", z.real, "| Imaginary:", z.imag)
Int Value: 987654321012345678909876543210 | Type:Float Value: 3.14159 | Type: Scientific Float: 25000.0 | Type: Complex Value: (3+5j) | Real: 3.0 | Imaginary: 5.0
2. Text Sequence Type (`str`)
A String (str) is an immutable sequence of Unicode characters. Strings can be declared using single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' / """...""") for multi-line text block definitions.
3. Boolean Type (`bool`)
The bool data type represents truth values: True or False. Notice the strict capitalization—true or false in lowercase trigger a NameError.
Internally, bool is a direct subclass of int. True evaluates to 1 and False evaluates to 0 in numerical calculations.
4. The Null / Absence Type (`NoneType`)
Python includes a special singleton value named None (an instance of NoneType) used to signal the absence of a value, an uninitialized variable state, or a default function return.
3. Mutability vs Immutability in Built-in Types
Understanding object mutability is one of the most vital architectural concepts in Python programming:
- Mutable Objects: Objects whose internal state or elements can be altered in place after creation without changing their memory address (e.g.,
list,dict,set,bytearray). - Immutable Objects: Objects whose internal state cannot be modified after instantiation (e.g.,
int,float,bool,str,tuple,frozenset,bytes).
Summary Matrix of Core Built-in Data Types
| Data Type | Class Name | Mutability | Example Literals |
|---|---|---|---|
| Integer | int |
Immutable | 10, -45, 0 |
| Float | float |
Immutable | 3.14, -0.001, 2.0 |
| String | str |
Immutable | "Hello", 'Python' |
| Boolean | bool |
Immutable | True, False |
| List | list |
Mutable | [1, 2, "three"] |
| Tuple | tuple |
Immutable | (1, 2, 3) |
| Dictionary | dict |
Mutable | {"key": "value"} |
| Set | set |
Mutable | {1, 2, 3} |
| None | NoneType |
Immutable | None |
4. Type Conversion Mechanics
Data processing frequently requires transforming data from one type to another (for instance, converting a string received from user terminal input into an integer for mathematical processing). Python supports two mechanisms:
- Implicit Type Conversion (Coercion): Automatic type conversion performed silently by the interpreter.
- Explicit Type Conversion (Type Casting): Manual type conversion performed by the developer using constructor functions.
5. Implicit Type Conversion (Automatic Coercion)
Implicit type conversion occurs automatically during mixed-type arithmetic operations. Python automatically converts lower-precision data types into higher-precision data types to prevent data loss.
Rules of Implicit Coercion:
- If an operation mixes an
intand afloat, the integer is promoted to afloatbefore performing the operation. - In operations mixing numerical types with
complexnumbers, the output promotes to acomplextype.
num_int = 15 # Type: int
num_float = 4.5 # Type: float
# Addition promotes result automatically to float
result = num_int + num_float
print("Result Value:", result)
print("Result Data Type:", type(result))
Result Value: 19.5 Result Data Type:
"Age: " + 25 raises a TypeError: can only concatenate str (not "int") to str. You must perform explicit casting.
6. Explicit Type Conversion (Type Casting)
Developers perform explicit type casting using built-in constructor functions: int(), float(), str(), bool(), list(), tuple(), and set().
1. The `int()` Constructor
Converts a compatible numeric or string value into an integer:
- From
float: Truncates decimal digits toward zero (does NOT round up or down). - From
str: Converts clean numeric text strings (e.g.,"123"). String values containing floats or letters (e.g.,"123.45"or"abc") raise aValueError.
2. The `float()` Constructor
Converts an integer or valid numeric string into a floating-point number (appends .0).
3. The `str()` Constructor
Converts any Python object into its string text representation.
4. The `bool()` Constructor (Truth Value Testing)
Converts any value into a Boolean True or False. Python evaluates values according to explicit truthiness rules:
Falsy Values in Python (Evaluate to `False`):
- Constants:
None,False. - Numeric zeros:
0,0.0,0j. - Empty collections / sequences:
""(empty string),[](empty list),()(empty tuple),{}(empty dictionary),set()(empty set).
Truthy Values: Virtually all other non-zero numbers, non-empty strings, and non-empty collections evaluate to True.
# Converting Float to Int (Truncation check)
raw_score = 98.85
int_score = int(raw_score)
print("Truncated Int:", int_score) # Output: 98
# String to Numeric Parsing
str_num = "450"
converted_num = int(str_num)
print("Added Result:", converted_num + 50) # Output: 500
# Truthiness Evaluations
print("bool(0):", bool(0))
print("bool('Hello'):", bool("Hello"))
print("bool(''):", bool(""))
print("bool([]):", bool([]))
Truncated Int: 98
Added Result: 500
bool(0): False
bool('Hello'): True
bool(''): False
bool([]): False
7. Handling Input Parsing and Type Conversion Errors
The built-in input() function always captures user input as a text string (str), regardless of what characters the user types into the console terminal.
# Simulating input parsing logic
age_input_string = "25"
# Direct mathematical operation fails without explicit casting
# age_next_year = age_input_string + 1 <-- Raises TypeError!
# Explicit conversion step
numeric_age = int(age_input_string)
age_next_year = numeric_age + 1
print(f"Current Age: {numeric_age}, Next Year: {age_next_year}")
Current Age: 25, Next Year: 26
8. Frequently Asked Interview Questions with Answers
list, dict, set) allow modifying their contents in place without altering their memory address ID. Immutable objects (e.g., int, float, str, tuple) cannot be modified after creation; any modification operation instantiates a brand new object at a distinct memory address.
ValueError: invalid literal for int() with base 10: '99.99' because int() expects plain digit characters. To convert it safely, first cast the string to a float, then cast the float to an int: int(float("99.99")).
[] is considered empty and evaluates to False. However, a string containing a single space " " is a non-empty sequence containing one whitespace character, so bool(" ") evaluates to True.
input() function always returns data typed as a string (str), regardless of whether the user enters letters, numbers, or symbols.
True is an instance with value 1 and False is an instance with value 0. As a result, expressions like True + True evaluate to integer 2.
9. Homework & Practical Assignment
Task 1: Type Identification & Truthiness Audit
Determine the data type and Boolean evaluation (True or False) for each literal expression:
0.0"False"None3 + 4j[]
Task 2: Interactive Input Converter Script
Create a script named calculator_input.py inside your lesson_06 directory:
- Prompt the user to enter two string inputs representing product price and quantity.
- Convert price to
floatand quantity toint. - Calculate
total_cost = price * quantity. - Print a formatted string output displaying the calculated total cost rounded to 2 decimal places.
Task 3: Safe Parsing and Error Diagnostic
Write a script named type_casting_diagnostic.py that attempts to convert string "123.89" into an integer directly. Observe the raised ValueError, document it in code comments, and implement the correct two-stage conversion fix.
10. File & Workspace Directory Structure
Standard Course Workspace Layout:
Ensure all exercise files are stored inside their corresponding lesson directories:
python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
│
└── lesson_06/
├── numeric_types.py
├── implicit_conversion.py
├── explicit_casting.py
├── user_input_casting.py
├── calculator_input.py
└── type_casting_diagnostic.py
11. What We Will Learn Next
```
OnlineCBT