Python’s random module adds unpredictability without requiring you to implement random-number operations yourself. Import it, then use dot notation to call functions for numbers, selections, and rearrangements. section 34.1 section 35.3
Common operations include:
- random.random() returns a floating-point value from 0 inclusive to 1 exclusive. section 34.1 section 35.3
- random.randint(a, b) returns an integer from a through b, including both endpoints. section 34.1
- random.choice(L) selects one element from a list, while random.sample(L, n) selects a specified number without repeating an element. section 34.1 section 35.3
Simulating rock-paper-scissors
import random r = random.random() if r < 1/3: computer = "rock" elif r < 2/3: computer = "paper" else: computer = "scissors" The three ranges give each choice an approximate one-third chance. Comparing the computer’s choice with the user’s input completes the game. section 35.3
import random people = ["Ana","Bob","Carl","Doug","Elle","Finn"] print(random.choice(people))
Run a complete small example that chooses one person from a list at random. section 35.3
Random results can make testing harder because a program may behave differently each time. Set a seed when you need a repeatable sequence while debugging. section 35.3



