Numbers
Integers, floats, complex numbers, arithmetic, and the math module
Python ships with three numeric types: arbitrary-precision integers, IEEE 754 floats, and complex numbers. The operators are familiar, but there are a few surprises—especially around floating-point precision.
Every snippet on this page runs in your browser—no setup required.
Real-world context: Where numbers matter
Numbers are everywhere in code:
- Web apps: user IDs, timestamps, request counts, pagination offsets.
- Data pipelines: row counts, byte sizes, elapsed time, statistical aggregates.
- Finance: prices, quantities, tax rates (and where floats will bite you).
- Machine learning: weights, gradients, loss values, learning rates.
- Games: positions, velocities, health points, scores.
Understanding the quirks of Python's numeric types—especially the precision limits of floats—will save you from subtle bugs.
Integers
int has no fixed size: it grows to fit whatever value you give it. No overflow, no wraparound. This is one of Python's nicest features.
No integer overflow in Python
In languages like C or Java, integer types have fixed sizes (e.g., 32 or 64 bits), so 2 ** 100 would overflow. Python's int is limited only by available memory. This makes arithmetic safer and more predictable.
Integer literals support several bases:
Floats
float is a 64-bit IEEE 754 double-precision floating-point number. That's the same representation used by C, Java, JavaScript, and most other languages. It's fast and space-efficient, but it has precision quirks.
The 0.1 + 0.2 surprise
Why does 0.1 + 0.2 ≠ 0.3?
In binary, 0.1 is an infinitely repeating fraction (like 1/3 is 0.333... in decimal). A 64-bit float can only store a finite approximation. When you add two approximations, the error compounds. This is not a Python bug—it's how all IEEE 754 floating-point arithmetic works.
For safe float comparisons, use math.isclose:
import math
print(math.isclose(0.1 + 0.2, 0.3)) # TrueIEEE 754: The standard
IEEE 754 is the industry-standard specification for floating-point arithmetic, dating back to 1985. It defines how numbers are stored in binary, how operations are rounded, and how special values like inf and NaN work. Almost every modern CPU has hardware support for it.
When to avoid floats: finance
For exact decimal arithmetic—like money—use decimal.Decimal:
Always construct Decimal from strings
If you pass a float to Decimal, you inherit the float's precision error:
Decimal(0.1) # Decimal('0.1000000000000000055511151231257827021181583404541015625')Always pass a string: Decimal("0.1").
Fractions for exact rationals
For exact rational arithmetic (fractions), use fractions.Fraction:
Complex numbers
Python has built-in support for complex numbers using j (not i) for the imaginary unit.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | addition | 2 + 3 == 5 |
- | subtraction | 5 - 2 == 3 |
* | multiplication | 2 * 3 == 6 |
/ | true division | 7 / 2 == 3.5 |
// | floor division | 7 // 2 == 3 |
% | modulo | 7 % 2 == 1 |
** | exponentiation | 2 ** 10 == 1024 |
A common surprise: / always returns a float in Python 3, even when both operands are integers.
Floor division rounds toward negative infinity, which can surprise C programmers:
Augmented assignment operators work as expected:
The math module
math is in the standard library. It covers the usual suspects:
Banker's rounding
Python's round() uses "round half to even" (banker's rounding): when a number is exactly halfway between two integers, round to the nearest even number. This reduces bias in repeated rounding operations.
print(round(0.5)) # 0
print(round(1.5)) # 2
print(round(2.5)) # 2If you need different rounding behavior, use math.floor or math.ceil.
Random numbers
For non-cryptographic randomness, use random. For cryptography, use secrets.
Challenges
Write a function round_to_cents(amount) that takes a string representing a dollar amount (e.g., "19.996") and returns a Decimal rounded to two decimal places. Use Decimal and its .quantize() method with ROUND_HALF_UP.
Define a function gcd(a, b) that returns the greatest common divisor of two positive integers using the Euclidean algorithm. Do not use math.gcd—implement it yourself using a loop or recursion.
Write a function compound_interest(principal, rate, years) that calculates the final amount using the formula A = P * (1 + r)^t. rate is a decimal (e.g., 0.05 for 5%). Return a float rounded to 2 decimal places.
Check your understanding
What does 7 // -2 evaluate to?
-3
-4
3
An error
Why does 0.1 + 0.2 == 0.3 evaluate to False?
It is a bug in Python that has not been fixed yet.
Floats are stored in binary and cannot represent these decimals exactly.
The == operator does not work for floats.
Python rounds floats to two decimal places.
Which module should you use for exact decimal arithmetic in financial applications?
math
fractions
decimal
random
What is the result of 2 ** 1000 in Python?
A very large integer
A very large integer with no overflow
OverflowError
inf (infinity)
Numbers are straightforward once you know the precision gotchas. Strings are deceptively rich; that's next.