Last week's docking bay game had one big problem: the secret bay was always 7. After two rounds, everybody at Mission Control knew the answer.
"The computer needs to pick the number itself," Rocket says. "And it should be different every time, even for me."
Raven shakes a pair of dice in her hand and rolls them across the desk. "What do you notice?" she asks. "We know the answer will be from 1 to 6. We just cannot know which one."
Nova hovers over the dice. "Would you like a hint?" she asks. "Python comes with a whole library of modules. One of them is called random, and it is very good at dice."
Rocket types import random and starts exploring.
The standard library is the set of modules that come with Python. You do not install anything; you just import them. The random module makes unpredictable choices.
random.randint(1, 6) gives a whole number from 1 to 6. Both ends are included. random.choice(a_list) picks one item from a list.
# dice.py
import random
roll = random.randint(1, 6)
print("You rolled", roll)
crew = ["Rocket", "Raven", "Nova"]
print("Today's captain:", random.choice(crew)) Every run can give a different result, so there is no single right output. One run might show You rolled 4 and Today's captain: Raven.
# docking_random.py
import random
secret = random.randint(1, 10)
tries = 0
while True:
guess = int(input("Guess the docking bay (1 to 10): "))
tries = tries + 1
if guess == secret:
break
elif guess < secret:
print("Higher")
else:
print("Lower")
print(f"Docked in {tries} tries!") random.seed(42) at the top of a program makes random give the same sequence every run. That sounds odd, but it is very useful for testing: the same seed, the same rolls.
Remove the seed line when you want true surprises again.
With random, you cannot know the exact output. You can still know every possible output, and test that the program handles each kind.
# wind_roll.py
import random
wind = random.randint(0, 40)
print("Wind:", wind)
if wind > 30:
print("Too windy today")
else:
print("Launch window open") | Statement | True or false? |
|---|---|
| random comes with Python, so nothing needs installing. | ? |
| random.randint(1, 6) can give 0. | ? |
| random.seed(42) makes the same sequence each run. | ? |
| Without a seed, every run gives the same rolls. | ? |
You used the standard library to add surprise to your programs. Tomorrow you will roll thousands of dice and shuffle lists.