Python Numbers
Python supports three types of number. They are integers, floating point numbers and complex numbers. They are defined as:
- int
- float
- complex
ints or integers are positive or negative whole numbers without decimals. They can be of unlimited length.
Floats or floating point numbers are positive or negative with a decimal point.
complex numbers are written in the form x + yj where x is the real part and y is the imaginary part.
Number objects are created when a value is assigned into a variable.
Example:
num1 = 7 # int
num2 = 7.5 # float
num3 = 5 + 3j # complex
You can use the type() function to verify the type of an object.
Example:
num1 = 7 # int
num2 = 7.5 # float
num3 = 5 + 3j # complex
print(type(num1))
print(type(num2))
print(type(num3))
Output:
<class 'int'> <class 'float'> <class 'complex'>
Type Conversion
You can convert one type of number into another by using int(), float() and complex() methods.
Example:
num1 = 7 # int
num2 = 7.5 # float
num3 = 5 + 3j # complex
a = float(num1) # convert from int to float
b = int(num2) # convert from float to int
c = complex(num1) # convert from int to complex
print(a)
print(b)
print(c)
Output:
7.0 7 (7+0j)