Python Numbers
Python contains three numerical types :
int
float
complex
When you assign a value to a numeric type variable, it is created :
Example :-
x = 1 # int
y = 2.8 # float
z = 1j # complex
Example :-
In Python, use the type()
function to determine the type of any object :
x = 1
y = 2.8
z = 1j
print(type(x))
print(type(y))
print(type(z))
Output :-
<class 'float'>
<class 'complex'>
Int
An integer or Int is a whole number that can be positive or negative, has no decimals, and can be any length.
Example :- Integers :-
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output :-
<class 'int'>
<class 'int'>
Float
A float, also known as a "floating point number", is a number that contains one or more decimals and is positive or negative.
Example 1 :-Different types float values :-
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output :-
<class 'float'>
<class 'float'>
Scientific numbers with an "e" for the power of 10 can also be used as floats.
Example 2 :- Float values with scientific numbers
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output :-
<class 'float'>
<class 'float'>
Related Links
Complex
The imaginary part of complex numbers is represented by a "j" :
Example :- Complex floating values
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output :-
<class 'complex'>
<class 'complex'>
Type Conversion
The int()
, float()
, and complex()
functions allow you to convert from one type to another :
Example Convert from one type to another:
#convert from int to float:
x = float(1)
#convert from float to int:
y = int(2.8)
#convert from int to complex:
z = complex(x)
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Output :-
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
Note : Complex numbers can't be converted into another type.
Related Links
Random Number
The random()
function for Python is not provided, but the Python module is built-in and can be used to make random
numbers.
Example :- The random module is imported, displaying a random number from 1 to 9 :
import random
print(random.randrange(1, 10))
Output :-