Python Random Module
The Python random module is part of the standard library and provides functions in order to generate random numbers or to work with elements randomly from data structures. It is widely used for tasks like simulation, games, and also generating test data.
This is a detailed explanation about its features:
1. Generating Random Numbers
The random module consists of various functions that may be used to generate numbers. This module generates number using the PRNG(pseudo-random number generator), so the generated number is determinate but apparently random.
Key Functions:
random()
- Returns a random floating-point number in the range [0.0, 1.0).
- Example:
import random
print(random.random()) # Output: 0.37444887175646646 (example)
uniform(a, b)
- Returns a random floating-point number in the range [a, b] or [b, a].
- Example:
print(random.uniform(10, 20)) # Output: 12.345 (example)
randint(a, b)
- Returns a random integer in the inclusive range [a, b].
- Example:
print(random.randint(1, 10)) # Output: 7 (example)
randrange(start, stop[, step])
- Returns a randomly selected integer from the range defined by
start,stop, andstep. - Example:
print(random.randrange(0, 10, 2)) # Output: 2, 4, 6, or 8
getrandbits(k)
- Returns an integer with
krandom bits. - Example:
print(random.getrandbits(4)) # Output: 0-15
2. Working with Sequences
The random module offers functions to pick or shuffle elements in sequences like lists or tuples.
choice(seq)
- Returns a random element from a non-empty sequence.
- Example:
colors = ['red', 'blue', 'green']
print(random.choice(colors)) # Output: 'blue' (example)
choices(population, weights=None, *, k=1)
- Returns a list of
krandom elements from the population with optional weighting. - Example:
items = ['apple', 'banana', 'cherry']
print(random.choices(items, weights=[1, 2, 3], k=2))
sample(population, k)
- Returns a list of
kunique elements chosen from the population. - Example:
print(random.sample(range(1, 10), 3)) # Output: [4, 1, 9] (example)
shuffle(seq)
- Shuffles the elements of the sequence in place.
- Example:
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums) # Output: [5, 1, 3, 4, 2](example)
3. Setting the Random Seed
- You can control the randomness using
random.seed()for reproducibility. - Example:
random.seed(42)
print(random.random()) # Output: 0.6394267984578837 (example)
4. Gaussian and Other Distributions
The random module also provides functions for generating numbers based on specific probability distributions.
gauss(mu, sigma)
- Returns a random number with a Gaussian (normal) distribution.
- Example:
print(random.gauss(0, 1)) # Mean=0, Std. Dev.=1
expovariate(lambd)
- Returns a random number with an exponential distribution.
- Example:
print(random.expovariate(1.5))
betavariate(alpha, beta)
- Returns a random number with a beta distribution.
gammavariate(alpha, beta)
- Returns a random number with a gamma distribution.
5. Notes on Randomness
- Pseudo-Randomness: Numbers are not truly random; they are generated deterministically based on the algorithm and seed.
- Cryptographic Security: For secure random numbers, use the
secretsmodule.
Example Program: Dice Rolling Simulation
import random
def roll_dice():
return random.randint(1, 6)
for _ in range(5):
print(roll_dice())
This will simulate rolling a six-sided die five times.