Python Type Conversion

In this tutorial, you will learn about type conversion (implicit and explicit conversion) with the help of examples.

Python has support for different data types such as int, float, str, etc. Type conversion allows us to convert one data type to another.

There are two kinds of type conversion in Python:

  • Implict Type Conversion
  • Explicit Type Conversion

Implicit Type conversion

In Implicit type conversion, Python automatically converts one data type to another without any user involvement.

Example: Sum of Two numbers


# int data
cost = 12000
# float data
vat = 1600.45
total = cost + vat
print(total) # Output: 13600.45

Here, the datatypes of cost and vat variable are different. And we are trying to add these two types of data.

In this case, Python automatically converts 12000 (int) to 12000.0 (float) before performing the addition operation.


Example: Addition of String and Integer

num_int = 123
num_str = "456"
print(num_int+num_str)

Output

Traceback (most recent call last):
File "<string>", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

As you can see, the above program throws an error. This is a classic example of where implicit type conversion fails in Python.

Here, Python automatically cannot convert these two types of data to the same type. To fix this issue, we can use the explicit type conversion.


Explicit Type conversion

In explicit type conversion, we manually convert one data type to another. Explicit type conversion is also referred to as typecasting, as it changes or casts the data type of objects.

There are predefined functions like int(), float(), str(), etc. that let us perform explicit type conversion.

Example: Converting String to Integer

num_int = 123
num_str = "456"
# converting num_str to integer
# converting "456" to 456
num_str = int(num_str)
print(num_int + num_str)
# Output: 579

Here, we are converting the "456" string to its equivalent integer. Hence, the result is the sum of 123 and 456.

Example: Converting Integer to String

num_int = 123
num_str = "456"
# converting num_int to string
# converting 123 to "123"
num_int = str(num_int)
print(num_int + num_str)
# Output: 123579

Here, we are converting the 123 integer to its equivalent string. Hence, the result is the concatenation of '123' and '456'.

By the way, explicit type conversion is also referred to as typecasting, as it changes or casts the data type of objects.

Example: Error in Explicit Type ConversionInteger to String

num_int = 123
num_str = "456a"
# trying to covert num_str to integer
# Error! cannot convert "456a" to its equivalent integer
num_str = int(num_str)
print(num_int + num_str)

The above program results in an error because Python cannot convert "456a" to its equivalent integer (since it contains a character). In such cases, Python throws an error.

Did you find this article helpful?