Python
In this tutorial we will do some number conversion exercises in Python.
We have already covered Numbers in the previous tutorial so, feel free to check that out.
Python takes care of data type conversion for us to correctly evaluate an expression when mixed data types are present in it. This is also known as implicit type conversion.
But we will also have cases were we have to explicitly tell Python to convert a variable to a specific type. This is also known as explicit type conversion.
Following are the functions used to convert number data types.
int()
We use the int() function to explicitly convert a value to integer type.
Points to note!
In the following example we are converting values to int.
# variables x = "10" # converting from string to int y = 123.45 # converting from float to int # convert updated_x = int(x) updated_y = int(y) # output print("x:", x, "is", type(x)) print("updated_x:", updated_x, "is", type(updated_x)) print("y:", y, "is", type(y)) print("updated_y:", updated_y, "is", type(updated_y))
We will get the following output.
x: 10 is <class 'str'> updated_x: 10 is <class 'int'> y: 123.45 is <class 'float'> updated_y: 123 is <class 'int'>
float()
We use the float() function to explicitly convert a value to float type.
In the following example we are converting values to float.
# variables x = "3.14" # converting from string to float y = 123 # converting from int to float # convert updated_x = float(x) updated_y = float(y) # output print("x:", x, "is", type(x)) print("updated_x:", updated_x, "is", type(updated_x)) print("y:", y, "is", type(y)) print("updated_y:", updated_y, "is", type(updated_y))
x: 3.14 is <class 'str'> updated_x: 3.14 is <class 'float'> y: 123 is <class 'int'> updated_y: 123.0 is <class 'float'>
complex()
We use the complex() function to explicitly convert a value to complex type.
In the following example we are converting value x to complex form where x is the real part of the complex number.
x
# variable x = 10 # real part of the complex number # convert result = complex(x) # output print("x:", x, "is", type(x)) print("result:", result, "is", type(result))
x: 10 is <class 'int'> result: (10+0j) is <class 'complex'>
In the following example we are converting value x and y to complex form where x is the real part of the complex number and y is the imaginary part.
y
# variable x = 10 # real part of the complex number y = 20 # imaginary part of the complex number # convert result = complex(x, y) # output print("x:", x, "is", type(x)) print("y:", y, "is", type(y)) print("result:", result, "is", type(result))
x: 10 is <class 'int'> y: 20 is <class 'int'> result: (10+20j) is <class 'complex'>