Python support 3 data type for numbers:
complex. These can also be used as variables, but a number always has a data type.
In this article we'll discuss more about these data types for numbers, namely which exist, how to convert them and use them.
Related course: Complete Python Programming Course & Exercises
How to Create a Number Variable in Python?
The program below creates 3 variables of different data types, Python finds out the data type automatically.
x = 1 y = 1.33 z = 1 + 3j
The complex number has a real number and an imaginary number. The imaginary number is denoted with
How to find the type of a Number?
Using the type() function you can find the data type.
print(type(x)) print(type(y)) print(type(z))
Integers are whole numbers. They can be positive or negative. They must be without decimal values.
You can use the
int() function to get the integer representation of an object.
Lets look into some examples of creating integers in Python.
x = 5 print(type(x)) x = int("10") print(type(x))
This results in:
>>> %Run example.py <class 'int'> <class 'int'> >>>
int() method above converts a string to the type integer.
A floating point number contains decimal points, they can be positive or negative. You can use float() function to get the float representation of an object.
x = 1.5 y = float("1.5") print(x) print(type(x)) print(y) print(type(y))
Complex numbers are less usual outside of science and engineering. They have a real and imaginary part.
Complex numbers are another collection of numbers, you can get one by for example taking the sqrt of minus one.
x = 2 + 3j print(type(x)) x = -3 + 3j print(type(x)) x = complex(3,4) print(x)
<class 'complex'> <class 'complex'> (3+4j)
Python Numbers Type Conversion
You can convert variables by calling the methods
x = 2 print(float(x)) y = 2.0 print(int(y))
>>> %Run example.py 2.0 2
If you want to convert a complex numbers, you can use `complex() to convert an int or float to a complex number.
x = 2 print(complex(x)) y = 2.0 print(complex(y))
>>> %Run example.py (2+0j) (2+0j)