Numbers
Python has three built-in numeric types: int for whole numbers of any size, float for decimals, and complex for complex numbers. It also offers the decimal and fractions modules when you need exact arithmetic.
Integers
small = 42 negative = -7 big = 2 ** 100 readable = 1_000_000 print(big) print(readable) print(0b1010, 0o17, 0xFF)
1267650600228229401496703205376 1000000 10 15 255
Python integers have no size limit — they grow as large as memory allows. That's unusual: most languages overflow at around 9 quintillion. Binary (0b), octal (0o) and hexadecimal (0x) literals are all ints.
Floats
pi = 3.14159 tiny = 1.5e-6 huge = 2e10 print(tiny, huge) print(10 / 4) print(10 / 5) print(type(10 / 5))
1.5e-06 20000000000.0 2.5 2.0 <class 'float'>
Division with / always produces a float, even when the result is whole. Use // for integer (floor) division (lesson 12).
Floating-point precision
print(0.1 + 0.2) print(0.1 + 0.2 == 0.3) print(round(0.1 + 0.2, 2) == 0.3) import math print(math.isclose(0.1 + 0.2, 0.3))
0.30000000000000004 False True True
Floats are stored in binary, which can't represent most decimal fractions exactly — a limitation of computers in general, not Python. Compare floats with math.isclose(), round for display, and use Decimal (below) for money.
Useful built-in functions
print(abs(-12.5)) print(round(3.14159, 2)) print(round(2.5), round(3.5)) print(max(3, 9, 2), min(3, 9, 2)) print(sum([1.5, 2.5, 3])) print(pow(2, 10), divmod(17, 5))
12.5 3.14 2 4 9 2 7.0 1024 (3, 2)
Note round(2.5) is 2: Python uses "banker's rounding", which rounds halves to the nearest even number to avoid bias in large calculations. divmod(a, b) returns the quotient and remainder together.
Number methods
print((3.75).is_integer(), (4.0).is_integer()) print((255).bit_length()) print((0.75).as_integer_ratio()) print(int(3.99), int(-3.99))
False True 8 (3, 4) 3 -3
int() truncates towards zero; for rounding down use math.floor, for up math.ceil (lesson 48).
Special float values
import math inf = float("inf") nan = float("nan") print(inf > 10 ** 100, -inf < 0) print(nan == nan, math.isnan(nan)) print(1 / 3)
True True False True 0.3333333333333333
Unlike JavaScript, dividing by zero in Python raises an error instead of returning infinity: 1 / 0 raises ZeroDivisionError.
Exact arithmetic: Decimal and Fraction
from decimal import Decimal from fractions import Fraction print(Decimal("0.1") + Decimal("0.2")) print(Decimal("19.99") * 3) print(Fraction(1, 3) + Fraction(1, 6))
0.3 59.97 1/2
Decimal does base-10 arithmetic exactly, which is why financial software uses it. Always create decimals from strings — Decimal(0.1) would inherit the float's tiny error. Fraction keeps exact rational numbers.
Complex numbers
z = 3 + 4j print(z.real, z.imag, abs(z))
3.0 4.0 5.0
You'll rarely need these outside engineering and science, but they're built in.