Python Type Conversion and Type Casting
Python Type Conversion and Type Casting
Casting
In this article, you will learn about the Type conversion and uses of type
conversion.
Type Conversion
The process of converting the value of one data type (integer, string, float,
etc.) to another data type is called type conversion. Python has two types
of type conversion.
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.
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))
• We add two variables num_int and num_flo , storing the value in num_new .
• In the output, we can see the data type of num_int is an integer while
the data type of num_flo is a float .
• Also, we can see the num_new has a float data type because Python
always converts smaller data types to larger data types to avoid the
loss of data.
Now, let's try adding a string and an integer, and see how Python deals
with it.
print(num_int+num_str)
• As we can see from the output, we got TypeError . Python is not able to
use Implicit Conversion in such conditions.
• However, Python has a solution for these types of situations which is
known as Explicit Conversion.
Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to
the expression.
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
4. Explicit Type Conversion is also called Type Casting, the data types
of objects are converted using predefined functions by the user.