Python Type Conversion and Type Casting

Learn implicit and explicit data type conversions in python. Also learn various type functions used for type conversion and few examples of how to do the typecasting between various python data types.

1. Type Conversion

The process, by which one data type is converted to another data type, is called type conversion. Like most programming languages, Python also supports two types of type conversion:

  • Implicit Type Conversion
  • Explicit Type Conversion

2. Implicit Type Conversion

Implicit type conversion is referred to as the process where python automatically converts a value from one data type to another data type, without any user involvement.

Python always converts smaller data types to higher data types to avoid the loss of data.

Let us see few examples of how python converts the lower data types (e.g. int) to higher data types (e.g. float).

Example: Convert int to float

In given example, we are adding two numbers of different data types. First number is int and second number is float. When we add both numbers, the output number is automatically assigned to float data type to avoid any possible data loss.

int_val = 11
flo_val = 1.1

flo_sum = int_val + flo_val

print("datatype of flo_sum:", type(flo_sum))
print("value of flo_sum:", flo_sum)

Program output:

datatype of flo_sum: <class 'float'>
value of flo_sum: 12.1
  • In above program, int_val is of integer data type and flo_val is of float data type.
  • Adding a integer to float will result in float value. So the flo_sum, which stores the sum of int_val and flo_val, is automatically assigned the float type.
  • We can verify the ype and value of flo_sum in terminal output.

TypeError: Incompitable data type

In the previous example, we added integer to float. Both are numeric values and thus are compatible with each other. But when we try to operate on incompatible data types, we get the TypeError.

Lets understand it with an example. In this example, we will add an integer value to a string value. Then we will observe the output.

int_val = 11
str_val = "1.1"

val_sum = int_val + str_val

print("datatype of val_sum:", type(val_sum))
print("value of val_sum:", val_sum)

Program output:

Traceback (most recent call last):
  File "<string>", line 4, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • Notice the type error reported for unsupported operand type(s) because we wanted to add integer data type to a string data type.
  • Python implecit type conversion failed at this. But, python offers a solution for this type of data type conversions, known as, explicit conversion.

3. Explicit Type Conversion

In explicit type conversion, python uses inbuilt functions which convert a given data type to another required data type. It is also known as type casting because we explicitely cast an object from one type to another type using a predefined function such as int(), float(), str(), etc.

Let’s understand the explicit casting with a few examples.

Example: Adding integer to string data type

Last time we tried this in implicit conversion and got the TypeError message. Let’s solve it with explicit conversion now.

We will use str() function to convert a numeric type to string type. Then we will add both values. The result of the addition will be the string data type.

int_val = 11
str_val = "1.1"

val_sum = str(int_val) + str_val

print("datatype of val_sum:", type(val_sum))
print("value of val_sum:", val_sum)

Program output:

datatype of val_sum: <class 'str'>
value of val_sum: 111.1

Similarily, in above example, we can use float() function to convert the string value to float type. In this way the val_sum will be of type float after the addition is performed.

4. Type Conversion Functions

Let’s look at few predefined functions which can be used for explicit type casting in Python. All these functions will give TypeError if they are not able to do the type conversion correctly.

  • chr(number) – converts number to its corresponding ASCII character.
  • int(str, base) – converts any data type to integer. base specifies the base in which string is if data type is string.

    The default value of base is 10, if it is not specified.

  • float() – converts any data type to a floating point number.
  • ord() – converts a character to integer.
  • hex() – converts integer to hexadecimal string.
  • oct() – converts integer to octal string.
  • tuple() – converts the given data type to a tuple.
  • set() – converts the given data type to a set.
  • list() – converts the given data type to a list.
  • dict() – converts the given ordered tuple to a dictionary.
  • str() – converts the given data type to a string.
  • complex(real,imag) – converts real numbers to complex(real,imag) number.

5. Conclusion

  • Python provides implicit type conversion to convert one data type to another data type, without any loss of data.
  • When types are not compitable, Python needs us to provide one of predefined conversion functions as seen in explicit conversion.
  • If data types are not compitable, Python will throw TypeError.
  • Python prevent loss of data, only in implicit type conversion. In explicit type conversion, loss of data is possible. For example, when we convert from a float to integer value using int() function, the value after decimal point is lost.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.