The random module generates random numbers and choices: it is the basis of games, raffles and simulations. It is imported with import random.
Random numbers
import random
print(random.random()) # a decimal between 0.0 and 1.0 (1.0 not included)
print(random.randint(1, 6)) # an integer between 1 and 6, both included
print(random.uniform(1, 10)) # a decimal between 1 and 10
print(random.randrange(0, 10, 2)) # one of 0, 2, 4, 6, 8
Careful: randint(a, b) includes b, while range(a, b) and randrange(a, b) do not.
Choosing from a collection
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors)) # one random element
print(random.sample(colors, 2)) # 2 different random elements
random.shuffle(colors) # shuffles the list (modifies it)
print(colors)
choice(sequence)returns one element.sample(sequence, k)returns a list ofkdifferent elements, without repeating.shuffle(list)shuffles the list itself and returns nothing.
An example: rolling a die
import random
roll = random.randint(1, 6)
if roll == 6:
print("A six!")
else:
print(f"You got a {roll}")
Random, but reproducible: seed
The numbers from random are not truly random: a formula calculates them from an initial value called the seed. If you set the seed with random.seed, the sequence is always the same, which is very useful for debugging or testing a program:
random.seed(5)
a = random.randint(1, 100)
random.seed(5)
b = random.randint(1, 100)
print(a == b) # True: same seed, same number
Testing a program with random data
Since the result changes on each run, you cannot check for a specific value, but you can check properties that always hold:
n = random.randint(1, 6)
print(1 <= n <= 6) # always True
Practice in Six-sided die.