A dice
It can land on 1, 2, 3, 4, 5, or 6. You can't know which one.
09SUPERPOWERS ยท RANDOM
Sometimes we want a surprise: a dice roll, a random prize, a secret number. Python has a toolbox called random. First you bring it in with import.
IN REAL LIFE
Nobody knows the result before it happens. That is random.
It can land on 1, 2, 3, 4, 5, or 6. You can't know which one.
Close your eyes and pick one paper. Any name can come out.
A coin flip picks one of two sides. Each turn can be different.
LOOK FIRST
Brings the random toolbox into your program. Write it once, at the top.
Gives back a whole number from 1 to 6. Both ends count.
Picks one thing from a list, like a name from a hat.
STEP BY STEP
Each time you run it, the number can change.
import randomOpen the random toolbox.dice = random.randint(1, 6)Roll: the box dice keeps a number from 1 to 6, like 4.print("You rolled", dice)Shows something like: You rolled 4if dice == 6:A question, like in Choose a path. print("Lucky six!")Only shows when the dice gives 6.RUN IT
Guess first. Then run real Python and check.
import random
dice = random.randint(1, 6)
print("You rolled", dice)Which result can NOT appear?
PyBot's hint
Ready. Press Run Python.
Pyodide 314.0.3 runs CPython in your browser with WebAssembly.
Open-source under the Mozilla Public License 2.0. License
Now change one thing: Run it 5 times. Did you get the same number every time? Then change 6 to 20 for a giant dice.
YOUR TURN
Try each tiny question. A wrong answer becomes something to review.
Which way is random?
dice = random.randint(1, 6)
print(dice)PyBot forgot the first line. What happens?
random.randint(1, 3)Which numbers can it give back?
Which line flips a coin?
pets = ["cat", "dog", "fish"]
print(random.choice(pets))What can it show?
You run a dice program twice. Do you always get the same number?
for turn in range(3):
print(random.randint(1, 6))How many numbers does it show?
PyBot wants to pick a snack at random, but it forgot the toolbox. Make it show: Yummy!
Yummy!OUTPUT
Want a fresh start? Clear only this page.
Write import random once, at the top. Then randint picks a number and choice picks from a list. Each run can be different.