CodeMIRAI
0 XP

math and random

2 min read 6 runnable examples Quiz included

math

Python
import math

print(math.sqrt(2))
print(math.pow(2, 10), 2 ** 10)       # math.pow always returns a float
print(math.factorial(6))
print(math.gcd(48, 18))               # greatest common divisor
print(math.ceil(2.1), math.floor(2.9), math.trunc(-2.7))
print(math.isclose(0.1 + 0.2, 0.3))

Constants and trigonometry (angles in radians):

Python
import math

print(math.pi, math.e, math.tau)
angle = math.radians(30)              # degrees -> radians
print(round(math.sin(angle), 3))
print(round(math.degrees(math.pi / 4), 1))
print(math.hypot(3, 4))               # length of the hypotenuse
print(math.log(100, 10), math.log2(1024))

random

Python
import random

print(random.random())                 # float in [0, 1)
print(random.randint(1, 6))            # whole number from 1 to 6 inclusive
print(random.uniform(1.5, 2.5))        # float in a range
print(random.choice(["rock", "paper", "scissors"]))

Run it a few times: different results each time.

Samples and shuffling

Python
import random

deck = list(range(1, 11))
random.shuffle(deck)                   # shuffles the list in place
print(deck)
print(random.sample(range(1, 50), 6))  # 6 different numbers: a lottery draw
print(random.choices(["H", "T"], k=10))   # 10 picks, repeats allowed

Repeatable randomness with seed

Random numbers in programs are pseudo-random: generated by a formula from a starting value called the seed. The same seed gives the same sequence, which is essential for testing and for reproducible experiments:

Python
import random

random.seed(42)
print([random.randint(1, 100) for _ in range(5)])
random.seed(42)
print([random.randint(1, 100) for _ in range(5)])   # identical

A dice simulation

Python
import random
from collections import Counter

random.seed(7)
rolls = [random.randint(1, 6) + random.randint(1, 6) for _ in range(10_000)]
counts = Counter(rolls)
for total in range(2, 13):
    print(f"{total:2}: {'#' * (counts[total] // 50)}")

Seven is the most common total of two dice, and the simulation shows it.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.