There are three numeric types in Python:
int(Integer)float(Floating Point Number)complex(Complex Number)
Variables of numeric types are created when you assign a value to them.
Integer (int)
Integers are whole numbers, positive or negative, without decimals.
Example:
x = 10
y = -20
z = 123456
print(type(x))
Output:
<class 'int'>
Float (float)
Floats are numbers that contain a decimal point.
Example:
x = 10.5
y = -20.75
z = 35.0
print(type(x))
Output:
<class 'float'>
Float numbers can also be written using scientific notation:
x = 35e3
y = 12E4
z = -87.7e100
print(x)
print(y)
print(z)
Output:
35000.0
120000.0
-8.77e+101
Complex (complex)
Complex numbers are written with a j as the imaginary part.
Example:
x = 3 + 5j
y = 5j
z = -5j
print(type(x))
Output:
<class 'complex'>
Type Conversion
You can convert from one numeric type to another using:
int()float()complex()
Example:
x = 5
y = 2.5
a = float(x)
b = int(y)
c = complex(x)
print(a)
print(b)
print(c)
Output:
5.0
2
(5+0j)
Random Numbers
Python does not have a built-in function for generating random numbers, but it has a built-in module called random.
Example:
import random
print(random.randint(1, 10))
Output:
7
The output will be a random number between 1 and 10.
Number Operations
Example:
x = 10
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
Output:
13
7
30
3.3333333333333335
Check Number Type
Use the type() function to determine the type of a number.
Example:
x = 10
y = 10.5
z = 3 + 5j
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
Summary
- Python has three numeric types:
int,float, andcomplex. - Integers are whole numbers.
- Floats are numbers with decimal points.
- Complex numbers contain an imaginary part represented by
j. - Use
type()to check the number type. - Use
int(),float(), andcomplex()for type conversion. - The
randommodule can generate random numbers.