Python Numbers
Python provides three numeric types, integers, floats, and complex numbers, and switches between them automatically when needed.
Three numeric types
Whole numbers are integers of type int, numbers with a decimal point are floats of type float, and numbers with an imaginary part are of type complex. Python decides the type from how you write the literal, so 7 is an int while 7.0 is a float even though they represent the same quantity.
The numeric types
a = 15 # int
b = 4.5 # float
c = 2 + 3j # complex
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>Automatic conversion in arithmetic
When you combine an int and a float in the same expression, Python promotes the result to a float so that no precision is lost. The true division operator, a single slash, always returns a float even when both operands are integers.
Mixing ints and floats
total = 10 + 2.5 # int + float -> float
print(total) # 12.5
print(9 / 3) # 3.0, division always gives a float
print(9 // 3) # 3, floor division keeps it an intWriting numbers clearly
- Use underscores as digit separators for readability, for example 1_000_000.
- Write very large or very small floats with scientific notation, such as 1.5e6.
- Floats are stored in binary and can carry tiny rounding errors, so 0.1 + 0.2 is not exactly 0.3.
- Convert between types explicitly with int(), float(), and complex() when you need to.
Readable literals and float precision
big = 1_000_000
print(big) # 1000000
print(0.1 + 0.2) # 0.30000000000000004
print(round(0.1 + 0.2, 2)) # 0.3Exercise: Python Numbers
Which built-in numeric type represents whole numbers in Python?