Introduction
In Python programming, data is stored using different data types such as integers, floats, strings, lists, tuples, and more. While working with these data types, there are many situations where you need to convert one type of data into another. This process is known as type conversion.
For example, when taking user input using the input() function, Python returns the input as a string. If you want to perform mathematical operations on that input, you must first convert the string into an integer or float. Similarly, you may need to convert numbers into strings for display purposes.
What is Python Type Conversion?
Type conversion is the process of changing a value from one data type to another.
Python supports two types of type conversion:
- Implicit Type Conversion
- Explicit Type Conversion
Example:
age = "25"
Here, age is a string.
Convert it into an integer:
age = int(age)
Now age becomes an integer.
Type conversion helps programs work correctly when different data types need to interact.
Why is Type Conversion Important?
Type conversion is useful in many programming situations.
Benefits of Type Conversion:
- Allows mathematical operations on user input
- Improves data compatibility
- Prevents type-related errors
- Supports data processing and calculations
- Makes programs more flexible
Without type conversion, many Python operations would fail.
Types of Type Conversion
Python supports two main categories of type conversion.
1. Implicit Type Conversion
Python automatically converts one data type into another when necessary.
This process is called implicit type conversion.
Example:
num1 = 10
num2 = 5.5
result = num1 + num2
print(result)
print(type(result))
Output:
<class ‘float’>
Python automatically converts the integer value into a float before performing the addition.
2. Explicit Type Conversion
Explicit type conversion occurs when the programmer manually converts one data type into another using built-in functions.
Example:
age = "25"
age = int(age)
print(age)
print(type(age))
Output:
<class ‘int’>
This process is also called type casting.
Checking Data Types
Before converting data, it is often useful to check its type.
Example:
value = "100"
print(type(value))
Output:
Note: The type() function helps identify the current data type.
Converting String to Integer
The int() function converts a string into an integer.
Syntax:
int(value)
Example:
number = "100"
result = int(number)
print(result)
print(type(result))
Output:
<class ‘int’>
Converting Float to Integer
The int() function can also convert floats into integers.
Example:
price = 99.99
result = int(price)
print(result)
Output:
Notice that the decimal part is removed.
Converting Integer to Float
The float() function converts integers into floating-point numbers.
Example:
age = 25
result = float(age)
print(result)
print(type(result))
Output:
<class ‘float’>
Converting String to Float
Example:
price = "49.99"
result = float(price)
print(result)
Output:
Note: This conversion is useful when working with decimal values entered by users.
Converting Number to String
The str() function converts numbers into strings.
Example:
age = 25
result = str(age)
print(result)
print(type(result))
Output:
<class ‘str’>
Converting List to Tuple
The tuple() function converts a list into a tuple.
Example:
fruits = ["Apple", "Banana", "Mango"]
result = tuple(fruits)
print(result)
Output:
Converting Tuple to List
The list() function converts a tuple into a list.
Example:
colors = ("Red", "Green", "Blue")
result = list(colors)
print(result)
Output:
Converting List to Set
The set() function converts a list into a set.
Example:
numbers = [1, 2, 3, 3, 4]
result = set(numbers)
print(result)
Output:
Duplicate values are automatically removed.
Converting Set to List
Example:
numbers = {1, 2, 3, 4}
result = list(numbers)
print(result)
Output:
Converting String to List
The list() function converts a string into a list of characters.
Example:
name = "Python"
result = list(name)
print(result)
Output:
Converting Dictionary Keys to List
Example:
student = {
"name": "John",
"age": 20
}
result = list(student)
print(result)
Output:
Common Type Conversion Functions
| Function | Purpose |
|---|---|
| int() | Convert to integer |
| float() | Convert to float |
| str() | Convert to string |
| list() | Convert to list |
| tuple() | Convert to tuple |
| set() | Convert to set |
| dict() | Convert to dictionary |
| bool() | Convert to Boolean |
Boolean Type Conversion
The bool() function converts values into Boolean values.
Example 1:
print(bool(1))
Output:
Example 2:
print(bool(0))
Output:
Example 3:
print(bool("Python"))
Output:
Real-Life Example
Suppose an online shopping website receives the product quantity from user input.
Example:
quantity = input("Enter quantity: ")
quantity = int(quantity)
total_price = quantity * 500
print(total_price)
Output:
1500
Without converting the input to an integer, multiplication would not work correctly.
Practical Example
Calculate Total Marks:
math_marks = input("Enter math marks: ")
science_marks = input("Enter science marks: ")
math_marks = int(math_marks)
science_marks = int(science_marks)
total = math_marks + science_marks
print("Total Marks:", total)
Output:
Enter science marks: 90
Total Marks: 170
This example demonstrates the importance of type conversion when processing user input.
Advantages of Type Conversion
1. Data Compatibility
Allows different data types to work together.
2. Error Prevention
Reduces type mismatch errors.
3. Flexible Programming
Enables dynamic handling of user input and external data.
4. Better Data Processing
Makes calculations and data manipulation easier.
5. Improved Code Readability
Explicit conversions clearly indicate intended data types.
Common Mistakes
1. Converting Invalid Strings to Integers
Incorrect:
value = "Python"
print(int(value))
Output:
Only numeric strings can be converted to integers.
2. Forgetting to Convert User Input
Incorrect:
age = input("Enter age: ")
print(age + 5)
Output:
Correct:
age = int(input("Enter age: "))
print(age + 5)
3. Losing Decimal Values
Example:
price = 99.99
print(int(price))
Output:
The decimal portion is removed.
4. Assuming Type Conversion Changes Original Variable
Incorrect assumption:
age = "25"
int(age)
print(type(age))
Output:
Correct:
age = int(age)
5. Converting Empty Strings
Incorrect:
value = ""
int(value)
Output:
Conclusion
Python type conversion is a fundamental concept that allows developers to transform data from one type into another. Whether you are converting strings into numbers for calculations, numbers into strings for display, or lists into tuples for data management, type conversion plays a crucial role in writing flexible and efficient programs.
Python Type Conversion – Interview Questions
Q 1: What is type conversion in Python?
Q 2: What are the types of type conversion?
Q 3: Which function converts a value to integer?
Q 4: What is explicit type conversion?
Q 5: Can strings be converted to numbers?
Python TypeConversion – Objective Questions (MCQs)
Q1. What is type conversion in Python?
Q2. Which of the following functions converts a string to an integer in Python?
Q3. What will be the output of the following code?
x = 5.8
y = int(x)
print(y)
Q4. Which of the following converts a number into a string?
Q5. What is the result of the following code?
a = "100"
b = 20
print(int(a) + b)