Basics
Numbers
Python has int for whole numbers and float for approximate real-valued arithmetic. True division with / returns a float, even when both inputs are integers.
Source
count = 10
ratio = 0.25
print(count + 5)
print(count / 4)
print(ratio * 2)Output
15
2.5
0.5Floor division and modulo are useful when you need quotient and remainder behavior. Powers use **, not ^.
Source
print(count // 4)
print(count % 4)
print(2 ** 5)Output
2
2
32Complex numbers are built in. The literal suffix j marks the imaginary part.
Source
z = 2 + 3j
print(z.real, z.imag)Output
2.0 3.0Floating-point values are approximate, so == between expected and computed floats is rarely the right test. Compare with math.isclose (or work in decimal.Decimal) when the question is "are these the same number to within tolerance".
Source
import math
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(round(3.14159, 2))Output
0.30000000000000004
False
True
3.14Notes
- Python's
inthas arbitrary precision; it grows as large as memory allows. - Python's
floatis approximate double-precision floating point. - Use
/for true division and//for floor division. - Use
math.iscloseinstead of==for floating-point comparison; reach fordecimal.Decimalwhen exact decimal precision is the domain requirement.
See also
Run the complete example
Expected output
15
2.5
2
2
32
2.0 3.0
0.30000000000000004
False
True
3.14
Execution time appears here after you run the example.