Python: Type Conversion (Implicit & Explicit)


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.

Example:

num1=20
num2="30"
result=num1+num2
print(result)

Output:

Traceback (most recent call last):
  File “D:\Saurabh\Python\src\test.py”, line 3, in <module>
    result=num1+num2
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Solution

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.

Example:

num1=20
num2="30"
result=num1+int(num2)
print(result) 

Output:

50

Note:

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.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s