PY

Numbers

Python · 8 entries

Integers & Floats

syntax
x = 42      # int
y = 3.14    # float
example
count = 1_000_000
ratio = 0.618
print(type(count), type(ratio))
print(count + ratio)
output
<class 'int'> <class 'float'>
1000000.618

Note Underscores in numeric literals are ignored and serve as visual separators. Python ints have unlimited precision.

Arithmetic Operators

syntax
+ - * / // % **
example
print(17 / 5)
print(17 // 5)
print(17 % 5)
print(2 ** 10)
output
3.4
3
2
1024

Note / always returns a float. // is floor division (rounds toward negative infinity, not toward zero). So -7 // 2 gives -4, not -3.

abs() and round()

syntax
abs(number)
round(number, ndigits)
example
print(abs(-42.5))
print(round(3.14159, 2))
print(round(2.5))
print(round(3.5))
output
42.5
3.14
2
4

Note round() uses banker's rounding — it rounds to the nearest even number when the value is exactly halfway. This surprises many developers.

math Module Essentials

syntax
import math
example
import math
print(math.ceil(4.2))
print(math.floor(4.8))
print(math.sqrt(144))
print(math.log(100, 10))
print(math.pi)
output
5
4
12.0
2.0
3.141592653589793

Note math functions work on ints and floats but not on complex numbers. Use cmath for complex math operations.

Complex Numbers

syntax
z = real + imagj
example
z = 3 + 4j
print(z.real, z.imag)
print(abs(z))
output
3.0 4.0
5.0

Note abs() on a complex number returns its magnitude. Use the cmath module for complex-specific functions like phase and polar conversion.

Numeric Type Conversion

syntax
int(x)
float(x)
complex(real, imag)
example
print(int("42"))
print(int(9.99))
print(float("3.14"))
print(int("0xff", 16))
output
42
9
3.14
255

Note int() truncates toward zero (not floor). int('3.14') raises ValueError; convert to float first, then to int.

Decimal for Precision

syntax
from decimal import Decimal
example
from decimal import Decimal

# Floating point issue
print(0.1 + 0.2)

# Decimal precision
result = Decimal("0.1") + Decimal("0.2")
print(result)
output
0.30000000000000004
0.3

Note Always pass strings to Decimal(), not floats. Decimal(0.1) inherits the float imprecision. Critical for financial calculations.

Number Formatting

syntax
f"{value:format_spec}"
example
price = 1234567.891
print(f"{price:,.2f}")
print(f"{0.856:.1%}")
print(f"{42:08b}")
print(f"{255:#06x}")
output
1,234,567.89
85.6%
00101010
0x00ff

Note Format spec mini-language: comma for grouping, .Nf for decimal places, % for percent, b/o/x for binary/octal/hex.