01 / 20
π ? √ math rng

Python's math & random
Modules

Learn to harness Python's built-in modules for mathematical computations and random number generation: from \(\sqrt{x}\) and \(\pi\) to coin flips and shuffled lists.

Python

What Is a Module?

A module is a file containing Python definitions and statements that you can import into your own programs. Instead of writing every function from scratch, you use pre-built toolkits.

Python
import math
import random

The math Module: Overview

The math module provides access to mathematical functions defined by the C standard. It handles constants, powers & roots, trigonometry, logarithms, and more.

Constants
\(\pi\), \(e\), \(\tau\), \(\infty\)
Roots & Powers
\(\sqrt{x}\), \(x^y\), factorial
Trig & Logs
\(\sin\), \(\cos\), \(\log\), \(\log_{10}\)

The random Module: Overview

The random module generates pseudo-random numbers: values that appear random but are produced by a deterministic algorithm from a seed value.

Integers
randint, randrange
Floats
random(), uniform(a, b)
Sequences
choice, shuffle, sample

Two Ways to Import

Method 1
import math
print(math.sqrt(25))   # 5.0
Method 2
from math import sqrt, pi
print(sqrt(25))        # 5.0
print(pi)              # 3.14159...

Key math Functions

math Constants
\(\pi, e, \tau, \infty\)
Powers & Roots
\(\text{sqrt}, \text{pow}, \text{factorial}\)
Trigonometry
\(\sin, \cos, \tan, \text{radians}\)
Logarithms
\(\log, \log_{10}, \log_2\)
Rounding
\(\text{ceil}, \text{floor}, \text{trunc}\)

Key random Functions

random random()
float in \([0.0, 1.0)\)
randint(a, b)
int in \([a, b]\) inclusive
choice(seq) pick one element shuffle(lst) reorder in place uniform(a, b)
float in \([a, b]\)

math vs random: Key Distinction

math random
Purpose Exact computation Randomized values
Deterministic? Always Pseudo-random
Same input → output Same every time Different each run
Example math.sqrt(16) → 4.0 random.randint(1,6) → ?
Use case Geometry, physics Games, simulations

How to Apply These Modules

1
Identify the need: Do you need a precise calculation or a random value?
2
Import the module: Use import math or import random at the top of your file.
3
Call the function: Use dot notation: module.function(args).
4
Store or use the result: Assign the return value to a variable, print it, or pass it to another function.
5
Test edge cases: Check boundary values (e.g., \(\sqrt{0}\), negative inputs, empty lists for choice()).

Example 1: Circle Area

Compute the area of a circle with radius \(r = 7\) using \(A = \pi r^2\).

Python
import math

r = 7
area = math.pi * r ** 2
print(f"Area = {area:.2f}")
Area = 153.94

Example 2: Hypotenuse

Find the hypotenuse of a right triangle with legs \(a = 3\) and \(b = 4\) using \(c = \sqrt{a^2 + b^2}\).

Python
import math

a, b = 3, 4

# Method 1: manual formula
c1 = math.sqrt(a**2 + b**2)

# Method 2: built-in shortcut
c2 = math.hypot(a, b)

print(c1, c2)
5.0 5.0

Example 3: Dice Roller

Simulate rolling two six-sided dice and print their sum.

Python
import random

die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
total = die1 + die2

print(f"Rolled {die1} + {die2} = {total}")
Rolled 4 + 5 = 9   (your output will vary)

Example 4: Password Generator

Generate a random 8-character password from letters and digits using random.choices().

Python
import random
import string

chars = string.ascii_letters + string.digits
password = "".join(random.choices(chars, k=8))

print(f"Password: {password}")
Password: kT9xB2mQ   (your output will vary)

math Rounding: floor vs ceil vs trunc

Python
import math

x = 3.7
print(math.floor(x))   # 3  (round down)
print(math.ceil(x))    # 4  (round up)
print(math.trunc(x))   # 3  (toward zero)

y = -3.7
print(math.floor(y))   # -4 (round down)
print(math.ceil(y))    # -3 (round up)
print(math.trunc(y))   # -3 (toward zero)

Common Mistakes

✕ Forgetting to Import
Writing sqrt(25) without import math first causes a NameError.
✕ Degrees vs Radians
math.sin(90) does NOT give 1. Trig functions expect radians. Use math.radians(90) first.
✕ randint Boundaries
randint(1, 6) includes 6. Using randint(1, 7) to simulate a die gives 7 sometimes!

Quick Reference Table

Function Module Returns Example
\(\text{sqrt}(x)\) math float sqrt(9) → 3.0
\(\pi\) math float constant 3.14159...
\(\text{ceil}(x)\) math int ceil(2.3) → 3
\(\text{floor}(x)\) math int floor(2.9) → 2
\(\text{randint}(a, b)\) random int [a, b] randint(1, 10)
\(\text{choice}(\text{seq})\) random element choice([1,2,3])
\(\text{shuffle}(\text{lst})\) random None (in-place) shuffle(myList)

Question 1 of 5

What does math.sqrt(144) return?

Question 2 of 5

Which function would you use to pick a random item from a list colors = ["red", "blue", "green"]?

Question 3 of 5

What is the output of math.floor(-2.3)?

Question 4 of 5

To compute \(\sin(90°)\) correctly in Python, which code is right?

Question 5 of 5

What is the range of possible values returned by random.randint(1, 10)?