Python by Example

Numbers

Python's three numeric types: int (arbitrary precision), float (IEEE 754), and complex - plus Decimal for exact arithmetic.

Python has three built-in numeric types: int (arbitrary precision - no overflow), float (IEEE 754 double), and complex. The standard library adds decimal.Decimal for exact decimal arithmetic and fractions.Fraction for rational numbers.

int in Python has no fixed size, so it never overflows. Integer division uses //, the remainder operator is %, and pow(base, exp, mod) computes modular exponentiation efficiently without building a huge intermediate number.

2 ** 100          # 1267650600228229401496703205376 - exact, no overflow
 
10 // 3           # 3  (integer division, rounds toward negative infinity)
10 % 3            # 1  (remainder)
 
pow(2, 10, 1000)  # 24  (2**10 mod 1000, fast even for huge exponents)

float uses IEEE 754 binary representation, which cannot represent most decimal fractions exactly. The classic example: 0.1 + 0.2 is not 0.3. Use math.isclose(a, b) when comparing floats by tolerance rather than exact equality.

import math
 
0.1 + 0.2           # 0.30000000000000004
0.1 + 0.2 == 0.3    # False
 
math.isclose(0.1 + 0.2, 0.3)           # True  (relative tolerance 1e-9)
math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-6)  # True

decimal.Decimal stores numbers as exact decimal fractions - the same way humans write them. This makes it the right choice for money and accounting, where rounding rules matter. Pass values as strings to avoid inheriting float imprecision at construction time.

from decimal import Decimal, ROUND_HALF_EVEN, getcontext
 
Decimal("0.1") + Decimal("0.2")   # Decimal('0.3')  - exact
 
# Set rounding mode for the current thread's context
getcontext().rounding = ROUND_HALF_EVEN
 
price = Decimal("19.995")
price.quantize(Decimal("0.01"))   # Decimal('20.00')  - banker's rounding

In production

Never store monetary values as float - 0.1 + 0.2 != 0.3 ships production bugs that staging never catches; use decimal.Decimal with an explicit rounding mode (ROUND_HALF_EVEN for accounting). The small-integer interning trap means a is b returns True for integers in roughly -5 to 256 but False for larger values; always use == for numeric value comparison.

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free