The math and random Modules

math

import math

print(math.sqrt(49))
print(math.floor(4.7))
print(math.ceil(4.2))
print(math.pow(2, 10))
print(math.factorial(5))

Output

7.0
4
5
1024.0
120
FunctionWhat it does
math.sqrt(x)square root
math.floor(x)round down to a whole number
math.ceil(x)round up to a whole number
math.factorial(n)1 × 2 × … × n
math.pithe number π (3.14159…)

ceil is handy in real life: 23 people, 5 seats per car – how many cars?

import math
print(math.ceil(23 / 5), "cars needed")

Output

5 cars needed

random

The random module picks things by chance – great for games.

import random

print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))

cards = ["A", "K", "Q", "J"]
random.shuffle(cards)
print(cards)

Output (yours will be different – it's random!)

6
paper
['K', 'J', 'Q', 'A']
FunctionWhat it does
random.randint(a, b)a random whole number from a to b (both included)
random.choice(list)one random item
random.shuffle(list)mixes up the list in place
random.random()a random float between 0 and 1

Common mistake: random is fine for games, but never use it for passwords or security tokens – it's predictable. Use the secrets module for that: secrets.token_hex(16).

HOME LEARN COMMUNITY DASHBOARD