Introduction
The random module generates pseudo-random numbers for games, simulations, and testing.
Basic Random
import random
random.random() # Float in [0, 1)
random.randint(1, 10) # Integer in [1, 10]
random.randrange(0, 100, 2) # Even numbers 0-98
Sequences
lst = [1, 2, 3, 4, 5]
random.choice(lst) # Single random element
random.choices(lst, k=3) # Multiple with replacement
random.sample(lst, k=3) # Multiple without replacement
random.shuffle(lst) # In-place shuffle
Distributions
import random
random.gauss(0, 1) # Gaussian/normal distribution
random.uniform(0, 1) # Uniform distribution
random.triangular(0, 1) # Triangular distribution
# Weighted choices
weights = [0.1, 0.2, 0.3, 0.4]
random.choices(lst, weights=weights)
Practice Problems
- Generate random password
- Shuffle deck of cards
- Simulate dice rolls
- Generate weighted random samples
- Create random walk simulation