Numbers in Python
Numbers
Integers, floating-point numbers, and complex numbers fall under the Python numbers category. They are defined as int, float, and complex classes in Python.
Number stores numeric values. Python creates a Number of objects when a number is assigned to a variable. Complex numbers are written with a "j" as the imaginary part. To verify the type of any
object in Python, use the type() function.
There are total 3 types of number in python:
- int
- float
- complex
Example:
a = 10 # int
b = 12.8 # float
c = 10j # complex
How to check the type of number? To verify the type of any object in Python, use the function() function:
a = 30 #Integer type
print(a)
print(type(a))
a = 10.32 #Float type
print(a)
print(type(a))
a = 20+0j #Complex type
print(a)
print(type(a))
Python type conversion:
Python has the capability and feature to convert within an expression containing the mixture of different types of values internally.
- Type int(x) to convert x to a plain integer.
- Type long(x) to convert x to a long integer.
- Type float(x) to convert x to a floating-point number.
- Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
- Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
Example:
x = int(2.8)
print(x)
y = float(10)
print(y)
z = complex(20)
print(z)
Output:
2
10.0
(20+0j)
Random number:
A random () function used to make a random number from the given range.
import random
print(random.randrange(1, 6))