Python Numbers
Data Types Focus
Python Numbers
Integers, floats, complex, Decimal, and Fraction give you the range to model everything from counters to currency.
Numeric types
| Type | Description | Example |
|---|---|---|
int | Arbitrary precision integer | 42 |
float | IEEE 754 double precision | 3.1415 |
complex | Real + imaginary parts | 1 + 2j |
decimal.Decimal | Base-10 with exact precision | Decimal("0.10") |
fractions.Fraction | Rational numbers | Fraction(1, 3) |
Precision
0.1 + 0.2 == 0.30000000000000004
- Floats can't represent some decimals exactly.
- Use
Decimalfor money andFractionfor rational arithmetic.
Useful modules
import math
math.sqrt(2)
math.isclose(a, b)
import statistics
statistics.mean(values)