Random Numbers

The random module makes values that look random. They are useful for games and simulations. The values come from a calculation, so they are not truly random. That is what lets a seed repeat them.

import random

random.seed(7)
cards = ["map", "key", "coin", "rope"]
random.shuffle(cards)
print(cards)
print(random.randint(1, 6))
print(random.choice(cards))

Output:

['rope', 'key', 'map', 'coin']
6
rope

Here is what each common function does:

FunctionResult
randint(a, b)A whole number from a to b, including both
choice(values)One item picked from a sequence, such as a list
sample(values, k)A new list of k items, with no item picked twice
shuffle(values)Mixes up the order of the list itself

shuffle changed the order of the cards list itself. randint(1, 6) rolled a die, and choice picked one card. Run this program again and you get the same three lines, because of the seed.

A seed makes the values come out in the same order on every run. This helps when you test your code, or when a simulation should give the same result again. Leave out the seed when each run should be different.

Do not use random for passwords or security codes. Use the secrets module for that. It is made for values that must be hard to guess.

In the exercise, set the seed, draw two numbers, and pick a player.