← Back to course
Code Crew G6+ / Week 07 / Monday
1/6
Week 07 Β· The standard library

Monday

Rolling dice with random
// random and datetime
⏱ about 30 min

Monday: Rolling dice with random

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 random module

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.

WHAT CAN RANDOM DO?
  • Read the question.
  • Tap your answer.
Which numbers can random.randint(1, 6) give?
Can you predict exactly what dice.py prints next time?
Which line picks a random planet from planets?

The docking game, now random

# 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!")
With smart guessing (always pick the middle of what is left), what is the most guesses you need for 1 to 10?
WHY THIS EXERCISEHalving the possibilities each time finds any bay from 1 to 10 in at most 4 guesses.

Seeds

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.

At your computer
1. Type dice.py, save it and run it three times. Notice the results change.
2. Add random.seed(42) on the line after import random. Run it three times. What do you notice?
3. Remove the seed line.
4. Type docking_random.py, save it and play. Try the middle-guess strategy.

Practice: reason about random results

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")
WHAT COULD HAPPEN?
  • Read the question.
  • Tap your answer.
What is the biggest wind value this program can show?
Which message appears when wind is exactly 30?
Can one run show both messages?
How many different whole numbers can randint(0, 40) give?
What is the smallest value randint(5, 9) can give?
Which line picks one of three colors from colors? random.____(colors)
StatementTrue 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.?
WHY THIS EXERCISErandom is in the standard library, randint(1, 6) starts at 1, and only a seed makes runs repeat.

You used the standard library to add surprise to your programs. Tomorrow you will roll thousands of dice and shuffle lists.