Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 6

Built-in Data Types and Type Conversion

Recognise Python's core value categories, inspect types, and convert input safely when a calculation requires it.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 6: Built-in Data Types and Type Conversion

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.

Core Principle: Variables in Python do not have types; objects have types. A variable is simply a reference pointing to an object of a specific built-in class in memory.

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, where j represents $\sqrt{-1}$.
NUMERIC_TYPES.PY
# 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)
OUTPUT
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.

String Immutability: Once a string object is created in memory, its contents cannot be modified in place. Any operation that alters a string (e.g., lowercasing, concatenation) creates a brand new string object in memory.

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:

  1. Implicit Type Conversion (Coercion): Automatic type conversion performed silently by the interpreter.
  2. 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 int and a float, the integer is promoted to a float before performing the operation.
  • In operations mixing numerical types with complex numbers, the output promotes to a complex type.
IMPLICIT_CONVERSION.PY
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))
OUTPUT
Result Value: 19.5
Result Data Type: 
Limits of Implicit Conversion: Python will NOT implicitly coerce non-numeric types like strings with numbers. Attempting "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 a ValueError.

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.

EXPLICIT_CASTING.PY
# 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([]))
OUTPUT
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.

USER_INPUT_CASTING.PY
# 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}")
OUTPUT
Current Age: 25, Next Year: 26

8. Frequently Asked Interview Questions with Answers

Q1: What is the fundamental difference between Mutable and Immutable data types in Python?
Answer: Mutable objects (e.g., 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.
Q2: What happens when you attempt to cast a float string like `"99.99"` directly using `int("99.99")`?
Answer: Python raises a 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")).
Q3: How does Python evaluate the truthiness of an empty container like an empty list `[]` vs a string containing a single space `" "`?
Answer: An empty collection like [] 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.
Q4: What is the data type returned by Python's `input()` function by default?
Answer: The input() function always returns data typed as a string (str), regardless of whether the user enters letters, numbers, or symbols.
Q5: Why is `bool` considered a subclass of `int` in Python?
Answer: Historically in Python, Booleans were built upon integer representations where 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:

  1. 0.0
  2. "False"
  3. None
  4. 3 + 4j
  5. []

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 float and quantity to int.
  • 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

Next Up: Lesson 7 — Numbers, Operators and the Math Module

Now that you master Python's built-in data types and conversion rules, we will explore mathematical processing capabilities in depth.

In the next lesson, we will cover:

  • Arithmetic Operators: Addition, Subtraction, Multiplication, True Division (/), Floor Division (//), Modulus (%), and Exponentiation (**).
  • Operator Precedence and Associativity rules (PEMDAS).
  • Built-in numeric functions: abs(), round(), pow(), min(), and max().
  • Working with Python's standard `math` module (e.g., math.ceil(), math.floor(), math.sqrt(), math.pi).

```

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat