python · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The module rolls dice, and a makes it repeatable.
import random gives you chance. random.randint(1, 6) rolls a dice, and both ends count. random.choice(prizes) picks one item from a list, and random.shuffle(cards) mixes a list up where it is.
Computers fake chance with a recipe that starts from a seed. Call random.seed(7) first, and the rolls that follow are the same on every single run.
That sounds like cheating, but it is how you test a game: same seed, same rolls, same result to check.
import random
random.seed(7)
roll = random.randint(1, 6)
print(f"You rolled a {roll}")
random.seed(7)
print(roll == random.randint(1, 6)) Leave the seed out of a real game, so every game is different.
guess first
The same seed, twice over. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import random
random.seed(42)
first = random.choice(["red", "green", "blue"])
random.seed(42)
second = random.choice(["red", "green", "blue"])
print(first == second)
your turn
Your turn. Pull a winner from a hat.
Type any seed number, and put at least three names in the hat. Then fill in the function that picks one item from a list.
fix it
The dice test fails. Can you fix the dice?
- Read the message after AssertionError. Which number came up that a dice does not have?
randintincludes both of its ends, sorandint(0, 6)can roll a 0.- Change randint(0, 6) to randint(1, 6) on line 3, then run.
nailed it
you tamed the dice. :D
random.randint(1, 6)includes both of its ends.random.choicepicks an item,random.shufflemixes a list.- The same seed always gives the same results.
new words in your collection
- random
- seed
This lesson isn’t saved. A free account remembers every lesson you finish.