The Type Conversion is the process of converting the value of one data type to another data type. In general, Type Conversion classified into two types
In Implicit type conversion, Python interpreter automatically converts one data type to another data type.In this Type Conversion the python interpreter converts lower datatype to higher datatype to avoid data loss.
num1 = 15 #int
num2 = 4.5 #float
num3 = num1 + num2
print("Value of num3:",num3)
print("Datatype of num3:",type(num3))
Value of num3: 19.5
datatype of num3: <class 'float'>
In the above example, we are trying to add two variable values(num1 is integer datatype & num2 is folat datatype),but resultant variable(num3) is float datatype, because python interpreter converts lower datatype(integer) to higher datatype(float) to avoid data loss.
In Explicit type conversion, The user converts one data type to another data type.In this Type Conversion the user converts higher datatype to lower datatype or lower datatype to higher datatype.
An Explicit type conversion is also called as Type Casting in Python
Python supports following functions to perform Type Casting in Python,
Those are
int ()
: This function converts any data type to integer.float()
: This function is used to convert any data type to a floating point number.str()
: This function is used to convert any data type to a string.a = int(2) # returns 2
b = int(3.2) # returns 3
c = int("6") # returns 6
d = int("11010",2) # returns base 2 value
print(a)
print(b)
print(c)
print(d)
2
3
6
26
a = float(2) # returns 2.0
b = float(3.2) # returns 3.2
c = float("6") # returns 6.0
d = float("6.2") # returns 6.2
print(a)
print(b)
print(c)
print(d)
2.0
3.2
6.0
6.2
a = str("abc") # returns 'abc'
b = str(3.2) # returns '3.2'
c = str(6) # returns '6'
print(a)
print(b)
print(c)
abc
3.2
6
Note: In Python, when an integer value is cast to float value, then it is appended with the fractional part containing zeros (0) and when a float value is cast to an integer it rounding down to the previous whole number.