Lesson 3 of 6 · Modules and the Standard Library · 2 min read · Updated

math and random

Built-in number helpers, the math module, and choosing things at random.

Built in, no import needed

python
print(abs(-7), pow(2, 5), divmod(17, 5))
print(round(7.456, 1), min(4, 9, 2), max([3, 8, 1]))
Output
7 32 (3, 2)
7.5 2 8

The math module

python
import math

print(math.ceil(4.1), math.floor(4.9))
print(math.sqrt(2))
print(math.pi)
print(math.gcd(12, 18), math.factorial(5))
print(math.isclose(0.1 + 0.2, 0.3))
Output
5 4
1.4142135623730951
3.141592653589793
6 120
True

ceil rounds up and floor rounds down, always. math.isclose() is the right way to compare floats — remember that 0.1 + 0.2 == 0.3 is False.

The random module

python
import random

print(random.randint(1, 6))        # a dice roll: 1 to 6, both included
print(random.random())             # a float from 0 up to 1
print(random.choice(["idli", "dosa", "poori"]))

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)              # shuffles the list itself
print(cards)
print(random.sample(range(1, 50), 6))  # 6 different numbers

The output changes every run — that is the point, so no fixed output is shown here. Note that randint(1, 6) includes 6, unlike range().

Note

Call random.seed(42) first and the same "random" numbers come out on every run — useful when testing a program. For passwords or security tokens use the secrets module instead; random is predictable by design.

What can random.randint(1, 3) return?

Try this now

  1. Write a number-guessing game: the computer picks 1 to 100 and says "higher" or "lower" until you guess.
  2. Simulate 600 dice rolls and count how often each face comes up.
  3. Work out the area of a circle for a radius the user types, rounded to 2 places.

Create a free account to save your progress, or sign in.