Numbers and arithmetic

Python · Essentials · 8 min

Numeric code is everywhere, and the int/float and division rules are where beginners trip up.

Python's int has arbitrary precision: 2 ** 200 just works, with no overflow. A float is an IEEE-754 double, so it has about 15–17 significant digits and cannot represent most decimal fractions exactly.

The operators:

  • + - * as usual; mixing an int and a float gives a float
  • / is true division and always returns a float: 7 / 2 == 3.5, 4 / 2 == 2.0
  • // is floor division, rounding toward negative infinity: 7 // 2 == 3, -7 // 2 == -4
  • % is the remainder, with the sign of the divisor: -7 % 2 == 1
  • ** is exponentiation; divmod(a, b) returns (a // b, a % b) in one go

Augmented assignment (total += 5, n *= 2) rebinds the name to the result.

Because floats are binary, 0.1 + 0.2 == 0.3 is False. Compare floats with math.isclose(a, b), and use the decimal module for money or anything that must match human decimal arithmetic exactly. round(2.5) returns 2 because Python rounds half to even ("banker's rounding"), which avoids systematic bias.

Underscores make long literals readable: 1_000_000. Other handy built-ins are abs(), min(), max(), sum() and pow(base, exp, mod) for fast modular powers. The math module adds sqrt, floor, ceil, pi, inf and friends.

Example

import math
from decimal import Decimal

print(7 / 2, 7 // 2, 7 % 2)      # 3.5 3 1
print(-7 // 2, -7 % 2)           # -4 1
print(2 ** 100)                  # 1267650600228229401496703205376
print(divmod(17, 5))             # (3, 2)

print(0.1 + 0.2 == 0.3)               # False
print(math.isclose(0.1 + 0.2, 0.3))   # True
print(Decimal("0.1") + Decimal("0.2"))  # 0.3

print(round(2.5), round(3.5))    # 2 4
print(1_000_000 * 3)             # 3000000

Remember

  • / always gives a float; // floors toward negative infinity
  • ints never overflow; floats are approximate binary doubles
  • Compare floats with math.isclose, use Decimal for exact decimal math

Watch out for

  • Testing floats with == after arithmetic.
  • Expecting round(2.5) to be 3 — Python rounds half to even.

Check yourself

  1. What does `-7 // 2` evaluate to?
  2. Which expression is a float?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex