Types of numbers in Python
Python has three built in numeric data types-
-
Integer (
int
) -
Floating-point numbers (
float
) -
Complex (
complex
)
Out of these, integers and floating-point numbers are used more commonly than complex number types.
1. Integer (int
)-
An int
is a whole number, positive or negative, of unlimited
length without any decimals. If a floating point number is to be converted to
int
, the digits after the decimal point are just removed, and
not rounded off.
For example -
num=245 print(type(num))
The output-
<class 'int'>
More about type()
in a future post.
2. Floating-point numbers (float)-
A floating-point number is a number with a decimal point.
For example-
num=14.87 print(type(num))
The output-
<class 'float'>
3. Complex numbers (complex
)-
A complex number is a number that has two components: A real element and an
imaginary one.
Python is one of the few coding languages that provides
built-in support for complex numbers.
For example-
num=1+2j print(type(num))
The output-
<class 'complex'>
Python puts the complex number in brackets to eliminate any confusion of it
being a arithmetic expression.
To find the real and imaginary element
from a complex number, we can do the following-
num=1+2j print(num.real) print(num.imag)
The output-
1.0 2.0
We can also get the complex conjugate of a number in the following way-
num=1+2j print(num.conjugate())
The output-
(1-2j)
Other Ways to Define Numbers
Numbers can also be defined in the following ways-
Exponential Notation
num=2e4 print(num)
The output
20000.0
Here, the e
notation multiplies the value before it with
10x, where x
is the number after e
.
Underscores
num=1_000_000 print(num)
The output-
1000000
Underscores between numbers are ignored by the Python interpreter. So, doing this helps the programmer identifying large numbers easily, in case they have to do it manually.
That is all for today's post on Python numbers. Hope it was informative and easy to understand. Drop a comment below if you have any suggestions, improvements, questions, etc.
Regards,
Aarav Iyer