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 # intnum2 = 7.5 # floatnum3 = 5 + 3j # complex
You can use the type() function to verify the type of an object.
Example:
num1 = 7 # intnum2 = 7.5 # floatnum3 = 5 + 3j # complexprint(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 # intnum2 = 7.5 # floatnum3 = 5 + 3j # complexa = float(num1) # convert from int to floatb = int(num2) # convert from float to intc = complex(num1) # convert from int to complexprint(a)print(b)print(c)
Output:
7.0 7 (7+0j)