Table of Contents
In this article, you will learn about the Type conversion and uses of type conversion.
Before learning Type Conversion in Python, you should have knowledge about Python Data Types.
Type Conversion
Type conversion is the process of converting the value of one data type (integer, text, float, etc.) to another data type. There are two types of type conversion in Python.
- Implicit Type Conversion
- Explicit Type Conversion
Implicit Type Conversion
The Python interpreter automatically changes one data type to another without the user’s intervention through implicit type conversion of data types. See the examples below for a better understanding of the subject.
Example 1: Converting integer to float
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
When we run the above program, the output will be:
datatype of num_int: <class 'int'> datatype of num_flo: <class 'float'> Value of num_new: 124.23 datatype of num_new: <class 'float'>
Explicit Type Conversion
In Python’s Explicit Type Conversion, the data type is manually modified by the user to suit their needs. The following sections describe various types of explicit type conversion:
- int(a, base): Converts any data type to an integer with this function. If the data type is a string, ‘Base’ defines the base in which string is stored.
- float(): Convert any data type to a floating-point number with this method.
Example 1: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
When we run the above program, the output will be:
Data type of num_int: <class 'int'> Data type of num_str before Type Casting: <class 'str'> Data type of num_str after Type Casting: <class 'int'> Sum of num_int and num_str: 579 Data type of the sum: <class 'int'>
Key Points to Remember
- The conversion of an item from one data type to another is known as type conversion.
- The Python interpreter does implicit type conversion automatically.
- Python prevents data loss during Implicit Type Conversion.
- Explicit Type Conversion, also known as Type Casting, is when the user converts the data types of objects using predefined functions.
- As we coerce the object to a certain data type with Type Casting, data loss is possible.