Lesson 21 of 30
Math and Random Modules
Mathematical functions, constants, and generating random numbers.
The math Module
import math
print(math.pi) # 3.14159...
print(math.e) # 2.71828...
print(math.sqrt(25)) # 5.0
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
print(math.log(100, 10)) # 2.0
print(math.factorial(7)) # 5040
print(math.sin(math.pi/2)) # 1.0
The random Module
import random
print(random.random()) # float in [0.0, 1.0)
print(random.randint(1, 6)) # dice roll (1–6)
print(random.uniform(1.5, 9.5)) # float in range
fruits = ["apple", "banana", "cherry"]
print(random.choice(fruits)) # random item
random.shuffle(fruits) # shuffle in place
print(random.sample(fruits, 2)) # 2 unique random items
Seeding for Reproducibility
random.seed(42)
print(random.randint(1, 100)) # always same value
Simulating a Coin Toss
results = {"heads": 0, "tails": 0}
for _ in range(1000):
flip = random.choice(["heads", "tails"])
results[flip] += 1
print(results)