Numbers, Booleans & Arithmetic
Python provides integers of unlimited size, binary floats, and exact numeric types for domains that cannot tolerate rounding error. Booleans participate in arithmetic because they subclass int.
Recipe
from decimal import Decimal
price = Decimal("19.99")
tax = Decimal("0.0825")
total = price * (1 + tax)
a, b = 7, 3
print(a / b, a // b, a % b, divmod(a, b))When to reach for this:
- Financial calculations requiring exact decimal semantics
- Scientific computing with floats and tolerances
- Bitwise flags and integer protocols
- Truth testing in
ifandwhileconditions
Working Example
from decimal import Decimal, ROUND_HALF_UP
from fractions import Fraction
def invoice_line(unit_price: str, qty: int, tax_rate: str) -> Decimal:
price = Decimal(unit_price)
tax = Decimal(tax_rate)
subtotal = price * qty
tax_amount = (subtotal * tax).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return subtotal + tax_amount
def float_trap() -> None:
print(0.1 + 0.2) # 0.30000000000000004
print(Fraction(1, 10) + Fraction(2, 10)) # 3/10 exact
def truthiness() -> None:
for value in [0, 1, "", "x", [], [0], None]:
print(repr(value), "->", bool(value))
if __name__ == "__main__":
print(invoice_line("19.99", 3, "0.0825"))
float_trap()
truthiness()What this demonstrates:
Decimalconstructed from strings avoids float binary artifactsquantizecontrols rounding for currency displayFractionkeeps rational numbers exact- Truthiness follows standard rules: zero, empty, and
Noneare falsy
Deep Dive
How It Works
- int - Arbitrary precision; only limited by memory.
- float - IEEE 754 double; fast but inexact for many decimals.
- Decimal - Base-10 floating point with configurable precision and rounding modes.
- bool - Subclass of
int;True == 1,False == 0. - Operator precedence - Standard PEMDAS; use parentheses for clarity.
Operators at a Glance
| Operator | Meaning | Notes |
|---|---|---|
/ | True division | Always returns float |
// | Floor division | Rounds toward negative infinity |
% | Modulo | Sign follows divisor in Python 3 |
** | Power | Large ints can grow quickly |
& | ^ << >> | Bitwise | On integers only |
Python Notes
import math
math.isclose(0.1 + 0.2, 0.3) # prefer over == for floats
int("ff", 16) # base conversion
float("nan") != float("nan") # NaN is not equal to itselfGotchas
- Float equality -
0.1 + 0.2 == 0.3is False. Fix:math.iscloseorDecimal. - Floor division on negatives -
-7 // 3is-3, not-2. Fix: Remember floor toward-inf. - Decimal from float -
Decimal(0.1)inherits float imprecision. Fix:Decimal("0.1"). - bool is int -
True + Trueequals 2. Fix: Do not use bools in sums unless intentional. - Large int to float - Converting huge ints to float loses precision. Fix: Stay in
intor useDecimal.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
Decimal | Money, tax, billing | Heavy scientific vector math |
Fraction | Exact rational math | Need transcendental functions |
numpy.float64 | Numeric arrays | Simple script arithmetic |
int only | Counting, indexing | Need fractional values |
FAQs
Why does 0.1 + 0.2 not equal 0.3?
Binary floats cannot represent 0.1 exactly. The sum is close but not identical - use isclose or Decimal.
When should I use Decimal vs float?
Decimal for currency and anywhere humans expect base-10 rounding. float for science, ML, and performance.
What is truthiness?
Objects define truth via __bool__ or __len__. Empty containers and zero numbers are falsy; most other objects are truthy.
How do I round for display?
from decimal import Decimal, ROUND_HALF_UP
Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)What does // do with negative numbers?
It floors: -7 // 3 is -3 because floor(-2.33) is -3.
Is bool a real integer?
bool subclasses int. isinstance(True, int) is True, but use bools only for logic, not counting.
How do I parse user numeric input safely?
Wrap int() / Decimal() in try/except ValueError, or validate with a schema library at API boundaries.
What is divmod for?
Returns (a // b, a % b) in one call - common for paging and clock arithmetic.
Can ints be infinitely large?
Yes in Python 3 - practical limit is memory. Crypto and bigint math rely on this.
How do bitwise operators work?
They operate on integer bit patterns - useful for flags, masks, and low-level protocols.
Related
- Variables, Types & Dynamic Typing - object types and identity
- Control Flow - truthiness in conditionals
- Strings & f-strings - formatting numbers in output
- Type Hints Basics - annotating numeric types
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.