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.
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.
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.
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.
Two Ways to Import
import math print(math.sqrt(25)) # 5.0
from math import sqrt, pi print(sqrt(25)) # 5.0 print(pi) # 3.14159...
Key math Functions
Key random Functions
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
import math or import random at the top of your file.module.function(args).choice()).Example 1: Circle Area
Compute the area of a circle with radius \(r = 7\) using \(A = \pi r^2\).
import math r = 7 area = math.pi * r ** 2 print(f"Area = {area:.2f}")
Example 2: Hypotenuse
Find the hypotenuse of a right triangle with legs \(a = 3\) and \(b = 4\) using \(c = \sqrt{a^2 + b^2}\).
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)
Example 3: Dice Roller
Simulate rolling two six-sided dice and print their sum.
import random die1 = random.randint(1, 6) die2 = random.randint(1, 6) total = die1 + die2 print(f"Rolled {die1} + {die2} = {total}")
Example 4: Password Generator
Generate a random 8-character password from letters and digits using random.choices().
import random import string chars = string.ascii_letters + string.digits password = "".join(random.choices(chars, k=8)) print(f"Password: {password}")
math Rounding: floor vs ceil vs trunc
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
sqrt(25) without import math first causes a NameError.math.sin(90) does NOT give 1. Trig functions expect radians. Use math.radians(90) first.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?
12.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)?
range(1, 10) which excludes the upper bound.