Typecasting / Type conversion is the process of converting one data type to another data type. There are two types of data type conversion.
- Explicit Conversion
- Implicit Conversion
Python Implicit Type Conversion
Implicit conversion occurs automatically whenever needed. It is converted from lower data type to upper data type.
val_1=2.5 val_2=5 val_3=val_1+val_2 print("The sum is ",val_3)
Output: The sum is 7.5
as you see two values are added integer and float the third data type is automatically storing float which is 7.5
Python Explicit Type Conversion
There are times when data types do not match each other, so we have to use built-in functions to convert them to other data types. In the following example, we are converting input string radius (“2.5”) into float data type.
pi=3.1416 radius=input("What is the radius?") radius=float(radius) area=2*pi*radius*radius print("The area of a circle is %.2f"%(area))
What is the radius?2.5
The area of a circle is 39.27
- int(x) : x is converted to integer
- float(x) : x is converted to float
- long(x) : x is converted to long data type
- tuple(x) : x is conveted to tuple
- str(x) : x is converted to string
Support us by sharing this post