Type Conversion
Contents
What is Type Conversion
Also called Type Casting , type conversion converts data from one data type to another. For example,
weight_1 = 25 # first kid's weight
weight_2 = 25.5 # second kid's weight
weight_total = weight_1 + weight_2
print ( weight_total )
50.5
type(weight_1)
int
type(weight_2)
float
When an int and float are added, Python automatically converts the final result to float.
type(weight_total)
float
Implicit Conversion
weight = 21.5
print ("weight = ", weight)
weight = 21.5
This is an example of implicit conversion done by Python. The variable weight is of type float. However, when we are printing it in the print statement, it is converted to a string and added with the prefix “weight = “. Here is another example – adding a complex number with a integer.
a = 1+2j
b = 2
c = a + b
type(c)
complex
Not all conversions are done automatically though. For example, when you get 2 numbers from the user as input and try to add them without explicit type casting, it does not work.
weight_1 = input() # python gathers the user's input as a string, not an integer
weight_2 = input()
weight_total = weight_1 + weight_2
print(weight_total)
2122
oops.. that is not what you expected, right ? here is why.
type(weight_1)
str
type(weight_2)
str
type(weight_total)
str
Explicit Conversion
weight_1 = input() # python gathers the user's input as a string, not an integer
weight_2 = input()
weight_total = int(weight_1) + int(weight_2)
print(weight_total)
43
This works because the input string gathered from the user is explicitly converted to an integer using the method int ( ). However, we would have a problem in adding weights with decimals. Try it. So, a better way would be to to an explicit type conversion to float.
weight_1 = input() # python gathers the user's input as a string, not an integer
weight_2 = input()
weight_total = float(weight_1) + float(weight_2)
print(weight_total)
44.0
a=input()
b = 2
c = a + b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-4a76891d8956> in <module>
2 b = 2
3
----> 4 c = a + b
TypeError: can only concatenate str (not "int") to str
a = int(input())
b = 2
c = a + b
a = 1
b = 2.5
c = a + b