Python Numbers
Python has three built-in numeric types: int, float, and complex. Numbers are created automatically when you assign a numeric value to a variable.
Three Numeric Types in Python
- int (Integer): Whole numbers—positive or negative, without decimals, and of unlimited precision (for example,
10,-42,1000000). - float (Floating Point): Numbers containing one or more decimals, or scientific notation using
eorE(for example,3.14,-0.5,2.5e3). - complex: Numbers written with a
jorJto represent the imaginary part (for example,3 + 5jor-2j).
Examples of Python Numbers
x = 15 # int
y = 19.99 # float
z = 2 + 4j # complex
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>
Scientific Notation in Floats
Floating-point numbers can use e or E to indicate powers of 10:
large_num = 1.5e4 # 1.5 * 10^4 = 15000.0
small_num = 2.0e-2 # 2.0 * 10^-2 = 0.02
print(large_num)
print(small_num)
Type Conversion Between Numbers
You can convert between int and float using int() and float() (note that complex numbers cannot be converted into int or float):
a = 10
b = 7.8
a_to_float = float(a) # 10.0
b_to_int = int(b) # 7 (truncates decimal part)
print(a_to_float, type(a_to_float))
print(b_to_int, type(b_to_int))
Tip: Python does not have a separate
random keyword built into the language syntax—import the standard random module when you need random numbers.