Tutorial

Type Conversions in Python

2 min read

In this article, we will discuss type conversions in Python programming. As we know Python is a dynamically typed language, which means that we don’t need to specify the type of a variable when we declare it.

But, sometimes we may need to convert a variable from one type to another. This process is called Type conversion.

There are two ways of doing this:

  1. Implicit Conversion – Python automatically converts the data type of variables.
  2. Explicit Conversion – The data type of variables are manually converted by the user.

In Python, type conversion can be done using the following built-in functions:

  1. int(): Converts a number or a string containing a number to an integer.
  2. float(): Converts a number or a string containing a number to a float.
  3. str(): Converts any data type to a string.
  4. bool(): Converts any data type to a boolean (True or False).

Converting String to Integer Data Type

Example of how to change string to integer in Python

a = '5'
b = int(a)
print(a)
print(b)

The output of this will be:

5
5

Here, we see that both variables a & b show the same output but their data types are different. The variable a is of string data type and b is an integer data type. We convert the string data to integer data using the int() function inside the variable b.

Arithmetic Operations Using Type Conversion in Python

Example of type conversion in Python using arithmetic operators

x = 5
y = '7'
z = x + int(y)
print(z)

The output of this will be:

12

Here, the variable z shows the sum of two different variables x & y, where x is an integer but y gets converted from string to integer during their operation using the int() function.

We can perform any kind of arithmetic operation using these types of conversion techniques.

Error & Exceptions of Type Conversion in Python

It’s important to note that type conversion functions will raise an exception if the value cannot be converted to the desired type. Moreover, there will be data loss if we try to do this.

Example of error and exception while try to change from one data type to another

x = 'hello'
y = int(x)

Here, Python will raise a ValueError exception because ‘hello’ cannot be converted to an int type.

In conclusion, type conversions in Python are useful for ensuring that variables of different data types can be used in multiple ways.

By using the built-in functions int(), float(), str(), and bool(), we can easily convert variables from one data type to another in our Python code.