Introduction
A significant part of programming involves playing around with data. While performing some tasks, situations might arise where the data type has to be changed from one type to another.
For example, if the variable is of type string, that has to be converted to int in order to perform arithmetic operations. In such a condition, the concept of type conversion and type casting comes into play.
Before learning Type Conversion and Type Casting in Python, you should be familiar with Python Data Types. So check out the blog Python Data Types for Beginners to get a better understanding.
Type Conversion
In type conversion, the Python interpreter automatically converts one data type to another. Since Python handles the implicit data type conversion, the programmer does not have to convert the data type into another type explicitly.
The data type to which the conversion happens is called the destination data type, and the data type from which the conversion happens is called the source data type.
In type conversion, the destination data of a smaller size is converted to the source data type of larger size. This avoids the loss of data and makes the conversion safe to use.
In type conversion, the source data type with a smaller size is converted into the destination data type with a larger size.
Let’s see an example to understand type conversion in Python.
intType = 20
floatType = 0.8
# intType is converted from int to float
result = intType + floatType
# intType is of type int
print("datatype of intType:", type(intType))
# floatType is of type float
print("datatype of floatType:", type(floatType))
print("intType + floatType = ", result)
# result is of type float
print("result: ", type(result))
Output:
datatype of intType: <class 'int'>
datatype of floatType: <class 'float'>
intType + floatType = 20.8
result: <class 'float'>
Let’s now try to add a string of larger size and int of smaller size.
intType = 20
strType = "0.8"
# add an integer and string
result = intType + strType
print("Data type of the listType :",type(intType))
print("Data type of the listType :",type(strType))
print("result: "+result)
print("Data type of the listType :",type(result))
Output:
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
As you might have guessed, we encountered a TypeError while running the above code. Python does not do the implicit conversion in this case. However, this error can be resolved using type casting, which will be discussed next.
Also See, Divmod in Python, Swapcase in Python