Python Type Conversion
In Python programming language type conversion is known as type casting means to convert one data type to another data type. In python or any other programming language, these are divided into two broad categories.
- Implicit Type Conversion
- Explicit Type Conversion
Implicit Type Conversion:
In this type of conversion, Python automatically converts one data type to another data type. This process doesn't need any extra code involvement.
Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.
Demo Example:
int_num = 100
float_num = 178.23
num_number = int_num + float_num
print("Data type of Int Number:",type(int_num))
print("datatype of num_flo:",type(float_num))
print("Value of converted number :",num_number)
print("Data type of converted number :",type(num_number ))
Explicit Type Conversion:
In this type of conversion, python converts the data type of an object to the required data type.
We use the python-predefined functions like int(), float(), str(), etc to perform explicit type conversion.
In this type of conversion is also called or known as type-casting because of the programmer casts (change) the data type of the objects.
Demo Example
"""
Example: Addition of string data type to integer datatype without typecasting
"""
int_number = 1567
str_number = "6575"
print("Data type of Interger Number:",type(int_number))
print("Data type of String Number:",type(str_number))
conveted_data=int_number+str_number
print("Value of converted data :",conveted_data)
print("Data type of converted data :",type(conveted_data ))
O/P:
conveted_data=int_number+str_number
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Addition of string and integer using explicit type casting
Syntax Structure :
new_type=(data type)data
Demo Example
"""
Example: Addition of string data type to integer datatype with typecasting
"""
int_number = str(1567)
str_number = "6575"
print("Data type of Interger Number:",type(int_number))
print("Data type of String Number:",type(str_number))
conveted_data=int_number+str_number
print("Value of converted data :",conveted_data)
print("Data type of converted data :",type(conveted_data ))
O/P:
Data type of Int Number: <class 'int'>
datatype of num_flo: <class 'float'>
Value of converted number : 278.23
Data type of converted number : <class 'float'>
Data type of Interger Number: <class 'str'>
Data type of String Number: <class 'str'>
Value of converted data : 15676575
Data type of converted data : <class 'str'>