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
| Function | What it does | Example |
|---|---|---|
abs(x) | Absolute value | abs(-5) → 5 |
round(x, n) | Rounds to n decimals | round(3.14159, 2) → 3.14 |
pow(x, y) | Power (like x ** y) | pow(2, 3) → 8 |
min(a, b, ...) | The smallest | min(3, 1, 2) → 1 |
max(a, b, ...) | The largest | max(3, 1, 2) → 3 |
divmod(a, b) | Quotient and remainder | divmod(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 form | Equivalent to |
|---|---|
x += 5 | x = x + 5 |
x -= 3 | x = x - 3 |
x *= 2 | x = x * 2 |
x /= 4 | x = x / 4 |
x //= 2 | x = x // 2 |
x **= 3 | x = x ** 3 |
x %= 5 | x = 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.