How to work with numbers
Use integers and floats
Integers are whole numbers of arbitrary size. Floats represent decimal values with finite binary precision.
items = 12
price = 2.50
print(type(items))
print(type(price))
Apply arithmetic operators
a = 10
b = 3
print(a + b, a - b, a * b)
print(a / b) # true division
print(a // b) # floor division
print(a % b) # remainder
print(a ** b) # power
Respect precedence
Exponentiation runs before multiplication and division, which run before addition and subtraction. Parentheses make intended order explicit.
subtotal = 20 + 5 * 2
with_grouping = (20 + 5) * 2
print(subtotal, with_grouping)
Round and compare carefully
Binary floats cannot exactly represent every decimal. Use round() for display and math.isclose() for approximate comparison.
import math
value = 0.1 + 0.2
print(value)
print(round(value, 2))
print(math.isclose(value, 0.3))