Arithmetic operators · 7 / 18 Theory

Numeric functions and the math module

Besides operators, Python includes ready-to-use functions for numbers. Some are always available and others live in the math module, which you have to import.

Functions that are always available

FunctionWhat it doesExample
abs(x)Absolute valueabs(-5) → 5
round(x, n)Rounds to n decimalsround(3.14159, 2) → 3.14
pow(x, y)Power (like x ** y)pow(2, 3) → 8
min(a, b, ...)The smallestmin(3, 1, 2) → 1
max(a, b, ...)The largestmax(3, 1, 2) → 3
divmod(a, b)Quotient and remainderdivmod(7, 2) → (3, 1)

The math module

To use its functions, write import math at the top of the program and then call them as math.name:

import math

print(math.pi)         # 3.141592653589793
print(math.sqrt(16))   # 4.0
print(math.floor(3.7)) # 3   (rounds down)
print(math.ceil(3.2))  # 4   (rounds up)

A typical example is calculating the area of a circle:

import math

radius = 3
area = math.pi * radius ** 2
print(area)   # 28.274333882308138

Some functions only accept certain values. For example, the square root of a negative number raises an error:

math.sqrt(-1)
# ValueError: math domain error

Augmented assignment operators

When you want to change a variable using its own value, you can shorten it:

Short formEquivalent to
x += 5x = x + 5
x -= 3x = x - 3
x *= 2x = x * 2
x /= 4x = x / 4
x //= 2x = x // 2
x **= 3x = x ** 3
x %= 5x = x % 5
total = 0
total += 10
total += 20
print(total / 2)   # 15.0

Practice in the exercises about the dimensions of a sphere and calculating the values of a function.