Python Arithmetic Operators
Arithmetic operators let you perform everyday math like addition, division, and exponentiation on numbers in Python.
Doing math in Python
Arithmetic operators work the way you would expect from a calculator, but Python adds a few useful extras such as floor division, modulo, and exponentiation. These operators work on integers and floating point numbers, and the type of the result depends on the operands you give them.
One detail worth remembering is that regular division with a single slash always produces a float, even when the numbers divide evenly. If you want a whole number result you use floor division with two slashes, which rounds down toward negative infinity.
Division, floor division, and remainder
print(10 / 4) # 2.5 (always a float)
print(10 // 4) # 2 (rounded down)
print(10 % 4) # 2 (the leftover remainder)
print(-10 // 4) # -3 (floor rounds toward negative infinity)The modulo operator is more useful than it first appears. Because it returns the remainder of a division, it is the standard way to test whether a number is even or odd, and to wrap values around a fixed range such as clock hours.
Practical uses of modulo and exponent
number = 17
if number % 2 == 0:
print("even")
else:
print("odd") # prints odd
area = 5 ** 2 # 5 squared
print(area) # 25
print(2 ** 0.5) # 1.4142135623730951 (square root of 2)- Use / when you want an exact result and are happy with a float.
- Use // when you need an integer count, such as how many full boxes fit.
- Use % to get the leftover, to detect even and odd numbers, or to cycle through values.
- Use ** for powers and roots instead of importing extra math functions.