Python Numbers
Python has three built-in numeric types: int for whole numbers, float for numbers with a fractional part, and complex for complex numbers. Python picks the type from how you write the number.
count = 12 # int
ratio = 0.75 # float
z = 3 + 4j # complex
print(type(count).__name__, type(ratio).__name__, type(z).__name__)int float complex
Integers
An int is a whole number, positive or negative, with no size limit. Python grows the number as large as memory allows, so you never get overflow:
big = 2 ** 100
print(big)
print(-17)
print(1_000_000 + 1)1267650600228229401496703205376
-17
1000001
You can also write integers in other bases:
| Prefix | Base | Example | Value |
|---|---|---|---|
0b |
binary | 0b1010 |
10 |
0o |
octal | 0o17 |
15 |
0x |
hexadecimal | 0xFF |
255 |
Floats
A float holds a decimal number. Any number with a . or an exponent e is a float:
print(2.5)
print(10.0)
print(1.5e3) # 1.5 × 10³
print(4e-2) # 4 × 10⁻²
print(7 / 2) # division always returns a float2.5
10.0
1500.0
0.04
3.5
Floating-point precision
Floats are stored in binary, so most decimal fractions are only approximated. This classic example surprises everyone once:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
import math
print(math.isclose(0.1 + 0.2, 0.3))0.30000000000000004
False
True
True
Tip: Never compare floats with
==after arithmetic. Round them, or usemath.isclose(). For money, use thedecimalmodule (shown below) or store cents as integers.
Arithmetic
| Operator | Meaning | 7 ? 2 |
|---|---|---|
+ |
addition | 9 |
- |
subtraction | 5 |
* |
multiplication | 14 |
/ |
true division | 3.5 |
// |
floor division | 3 |
% |
remainder (modulo) | 1 |
** |
power | 49 |
Mixing an int and a float gives a float. Useful built-ins:
print(abs(-8))
print(round(3.14159, 2))
print(round(2.5), round(3.5)) # rounds to the nearest even number
print(divmod(17, 5)) # (quotient, remainder)
print(pow(3, 4))
print(max(4, 9, 2), min(4, 9, 2))8
3.14
2 4
(3, 2)
81
9 2
round() uses "banker's rounding": exact halves go to the nearest even number, which avoids bias in large sums.
Complex numbers
Complex numbers are written with a j for the imaginary part. They are used in engineering and science:
z = 3 + 4j
print(z.real, z.imag)
print(abs(z)) # magnitude
print(z * (1 - 1j))3.0 4.0
5.0
(7+1j)
Exact decimals
The decimal module does base-10 arithmetic, so it gets money right:
from decimal import Decimal
price = Decimal("0.10")
print(price * 3)
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))0.30
True
Test yourself
What does 7 // 2 evaluate to?
- 3.5
- 3
- 4
- 1
What is the type of 10 / 2?
- int
- float
- complex
- decimal
Why is 0.1 + 0.2 == 0.3 False?
- Python has a bug
- Floats are stored in binary and can only approximate 0.1
- The == operator doesn't work on floats
- 0.3 is an int