Python Numbers



In Python, There are three different types of numbers in Python:

  • Integer
  • Float
  • Complex



Integers 

An integer is an Entire number that can be positive or negative.

# Following numbers are integers
x = 34
y = -23
z = 34567890

print(type(x))
print(type(y))
print(type(z))

Output :

<class 'int'>
<class 'int'>
<class 'int'>

 In Python 3, there is no limit to how long an integer value can be. It can grow to have as many digits as your computer’s memory space allows.


# Integers have unlimited accuracy
x = 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111



Float

Float is a positive or negative number with a fractional part.


Example :

# Following numbers are floats
x = 12.4
y = -16.5
z = 3.141592653589793238

print(type(x))
print(type(y))
print(type(z))

Output :

<class 'float'>
<class 'float'>
<class 'float'>

You can append the character e  followed by a positive or negative integer to specify the scientific sign.


Example :

# Scientific sign e
x =23e3
print(x)

y = 2.3e-3
print(y)

print(type(x))
print(type(y))

Output :

23000.0
0.0023
<class 'float'>
<class 'float'>

The maximum value a float can have is approximately 1.8×10308. Any number greater than that is indicated by the string inf (infinity)

The minimum value a float can have is approximately 5.0×10-324. Any number, less than that is considered zero.

 


Example :

# Maximum value of a float
a = 1.34e308
print(1.79e308)

b = 1.3e308
print(1.8e308)

# Minimum value of a float
c = 4e-324
print(5e-324)

d = 4e-325
print(5e-325)

print(type(a))
print(type(b))
print(type(c))
print(type(d))

Output :

1.79e+308
inf
5e-324
0.0
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>




Complex

A complex number is defined as  real-part + imaginary-part, where the imaginary part is written with a j or J.


Example :

# Following numbers are complex numbers
x = 4j
y = 5+2j

print(type(x))
print(type(y))

Output :

<class 'complex'>
<class 'complex'>

To extract real and imaginary parts from a complex number x, use x.real and x.imag


Example :

x = 5+2j

# Real Part
print(x.real)

# Imaginary Part
print(x.imag)

print(type(x))

Output :

5.0
2.0
<class 'complex'>




Type Conversion

Frequently, you will want to convert data from one type into another. In programming, we call this process typecasting.

you can convert one form to another form using this method: int()float(), and complex()


Example : 

a = 3
b = 2.1
c = 3j

# Convert int to float
x = float(a)

# Convert float to int
y = int(b)

# convert int to complex
z = complex(a)

print(x)
print(y)
print(z)

print(type(x))
print(type(y))
print(type(z))

Output :

3.0
2
(3+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

Note: You cannot convert complex numbers into another number type.