Python Numbers

Tutorial 6 of 65 · pythondeck.com Python course

Integers in Python have arbitrary precision. Floats follow IEEE-754 double precision. Use the decimal module for exact decimal arithmetic (money) and fractions for rational numbers. The complex type writes the imaginary part with j.

Numbers model quantities, indices, and measurements. Python provides arbitrary-precision integers, IEEE-754 doubles for floats, and complex numbers as a first-class type for scientific code.

Numeric bugs often come from float rounding, integer division changes in Python 3, or mixing Decimal with float without a clear policy for money and metrics.

int has unlimited precision; literals like 1_000_000 improve readability.

float is binary floating point; 0.1 + 0.2 may not equal 0.3 exactly.

/ always returns float; // is floor division; % follows floored quotient.

complex uses j for imaginary unit: 3 + 4j.

math module for transcendentals; cmath for complex; decimal.Decimal for base-10 control.

Builtins: abs, round, pow, divmod, min, max, sum.

For financial calculations, use decimal.Decimal with a context and quantize, not raw floats. For heavy numerics, NumPy arrays replace Python scalars in hot loops.

Random numbers belong to the random module or secrets for security—never use floats alone for cryptographic keys.

Comparisons chain: 0 < x < 10 is idiomatic; hex 0xFF and binary 0b1010 help with flags and masks.

Using float as a loop counter and accumulating rounding error.

Expecting // and % to match mathematical modulo for negative operands (floor division rules apply).

Comparing floats with == instead of math.isclose.

Parsing locale-formatted numbers (1,234.56) with bare int().

Use integers for counts and indices; floats for measurements with known tolerance.

Display floats with formatting (f"{x:.2f}") rather than relying on repr.

Import only the math functions you need or use math. prefix for clarity.

Document units in variable names (delay_seconds, price_cents).

Pick one numeric library per module—mixing Decimal and float in the same calculation invites bugs.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates big integers. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: Big integers
# Run in the REPL or save as a .py file and execute with python.
print(2 ** 200)

This sample walks through float precision in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Float precision
# Run in the REPL or save as a .py file and execute with python.
print(0.1 + 0.2)            # 0.30000000000000004
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))

Here is a hands-on illustration of complex numbers. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: Complex numbers
# Run in the REPL or save as a .py file and execute with python.
z = 2 + 3j
print(z.real, z.imag, abs(z))

The program below demonstrates arbitrary ints. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Python ints have no fixed bit width — they grow as needed
big = 2 ** 100  # hundred-bit exponentiation is instant
print(len(str(big)))  # count digits in decimal form
print(type(big))  # <class 'int'>
a, b = 10, 3  # operands for division demos
print(a / b)  # true division -> float 3.333...
print(a // b, a % b)  # floor division and remainder
print(divmod(a, b))  # tuple (3, 1) same as // and %
hex_id = 0xFF  # hexadecimal literal
print(hex_id, bin(hex_id))  # 255 0b11111111

This sample walks through decimal exactness in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Floats are binary approximations; Decimal fixes money math
from decimal import Decimal, getcontext  # stdlib exact decimal type
getcontext().prec = 28  # precision for financial calculations
price = Decimal("19.99")  # never build money floats from binary
tax_rate = Decimal("0.0825")  # eight and a quarter percent
tax = (price * tax_rate).quantize(Decimal("0.01"))  # round cents
total = price + tax  # still Decimal end-to-end
print(price, tax, total)  # inspect components
from fractions import Fraction  # rationals for exact ratios
half = Fraction(1, 3) + Fraction(1, 6)  # 1/2 exactly
print(float(half), half)  # 0.5 1/2

« Python Data Types All tutorials Python Strings »