Python Math
The math module covers everything you'd expect from a calculator: powers, logs, trig, and special constants.
Constants
PYTHON
import math print(math.pi) # 3.141592653589793 print(math.e) # 2.718281828459045 print(math.inf, -math.inf, math.nan) print(math.tau) # 2π
Common functions
| Function | Returns |
|---|---|
math.sqrt(x) | Square root. |
math.pow(x, y) or x ** y | Power. |
math.floor(x) / math.ceil(x) | Round down / up. |
math.log(x, base=e) | Logarithm. |
math.sin / cos / tan | Trig (radians). |
math.gcd(a, b) | Greatest common divisor. |
math.factorial(n) | n! |
math.hypot(*coords) | Euclidean distance from origin. |
math.isclose(a, b) | Float-safe equality. |
Don't use == on floats
PYTHON
print(0.1 + 0.2 == 0.3) # False — surprising! print(math.isclose(0.1 + 0.2, 0.3)) # True
Random
random is a separate module:
PYTHON
import random print(random.random()) # 0.0 ≤ x < 1.0 print(random.randint(1, 6)) # dice roll print(random.choice(['a','b'])) # pick one random.shuffle([1, 2, 3]) # in place
Tip: For cryptography use
secrets, not random. random is a deterministic PRNG — fine for games, not for tokens.Example
Example
import math print(math.pi) print(math.sqrt(2)) print(math.floor(3.7), math.ceil(3.2)) print(math.log(100, 10))Try it Yourself »
Exercise
Float-safe equality check.
math.
(a, b)
Seven letters; iscamelcased.
Discussion
Loading…