In Python, when we perform any operation on variables of different datatypes, the data of one variable will be converted to a higher datatype among the two variables and the operation is completed. This conversion is done by interpreter automatically and it is known as implicit type conversion. But Python does not support implicit type conversion of two different data types, and it will throw an error.
num1=20 num2="30" result=num1+num2 print(result)
Traceback (most recent call last):
File “D:SaurabhPythonsrctest.py”, line 3, in <module>
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
If we must avoid this, then we have to explicitly convert the datatype of one variable into the required data type to complete the operation. This is known as explicit type conversion.
num1=20 num2="30" result=num1+int(num2) print(result)
Programming languages define their own rules for implicit and explicit conversions. These rules will change from language to language.
Similarly, one has to be careful in explicit conversions as well. For example,
- Converting a floating-point value to integer would result in loss of decimal point values.
- A larger data type if converted to smaller data type will result in loss of data as the number will be truncated.