Python Tutorial · Working with Data · Lesson 33 of 42

Python Math

Built-in math functions, the math module, random numbers and statistics.

Built-in functions

Example 1Try it yourself
print(abs(-7))
print(round(3.14159, 2))
print(min(4, 9, 1), max(4, 9, 1))
print(pow(2, 10))
print(divmod(17, 5))

Output

7
3.14
1 9
1024
(3, 2)

The math module

Example 2Try it yourself
import math

print(math.pi)
print(math.sqrt(144))
print(math.ceil(4.1), math.floor(4.9))
print(math.gcd(24, 36))
print(math.factorial(5))
print(math.hypot(3, 4))

Output

3.141592653589793
12.0
5 4
12
120
5.0

Random numbers

The random module generates pseudo-random numbers. Setting a seed makes results repeatable (useful in tests). For passwords and tokens use the secrets module instead.

Example 3Try it yourself
import random

random.seed(42)
print(random.randint(1, 6))
print(random.choice(["red", "green", "blue"]))
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)

Output

6
red
[2, 4, 5, 3, 1]

Test yourself

Which module should you use to generate a secure password reset token?

  1. random
  2. math
  3. secrets
  4. uuid
Show answer

Answer: secrets