Syntaxx = 42
y = 3.14
Examplecount = 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.
Syntax+ - * / // % **
Exampleprint(17 / 5)
print(17 // 5)
print(17 % 5)
print(2 ** 10)
Output3.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.
Syntaxabs(number)
round(number, ndigits)
Exampleprint(abs(-42.5))
print(round(3.14159, 2))
print(round(2.5))
print(round(3.5))
Output42.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.
Syntaximport math
Exampleimport math
print(math.ceil(4.2))
print(math.floor(4.8))
print(math.sqrt(144))
print(math.log(100, 10))
print(math.pi)
Output5
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.
Syntaxz = real + imagj
Examplez = 3 + 4j
print(z.real, z.imag)
print(abs(z))
Output3.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.
complex numberimaginarymagnitudecmath
Syntaxint(x)
float(x)
complex(real, imag)
Exampleprint(int("42"))
print(int(9.99))
print(float("3.14"))
print(int("0xff", 16))
Output42
9
3.14
255
Note int() truncates toward zero (not floor). int('3.14') raises ValueError; convert to float first, then to int.
Syntaxfrom decimal import Decimal
Examplefrom decimal import Decimal
print(0.1 + 0.2)
result = Decimal("0.1") + Decimal("0.2")
print(result)
Output0.30000000000000004
0.3
Note Always pass strings to Decimal(), not floats. Decimal(0.1) inherits the float imprecision. Critical for financial calculations.
Syntaxf"{value:format_spec}"
Exampleprice = 1234567.891
print(f"{price:,.2f}")
print(f"{0.856:.1%}")
print(f"{42:08b}")
print(f"{255:#06x}")
Output1,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.