โ†Previous page

09SUPERPOWERS ยท RANDOM

Roll the dice!

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

Surprises in real life.

Nobody knows the result before it happens. That is random.

A dice

It can land on 1, 2, 3, 4, 5, or 6. You can't know which one.

Names from a hat

Close your eyes and pick one paper. Any name can come out.

Heads or tails

A coin flip picks one of two sides. Each turn can be different.

LOOK FIRST

Bring the toolbox, then use it.

import random

Brings the random toolbox into your program. Write it once, at the top.

random.randint(1, 6)

Gives back a whole number from 1 to 6. Both ends count.

random.choice(list)

Picks one thing from a list, like a name from a hat.

STEP BY STEP

A dice in a few lines.

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 4
if dice == 6:A question, like in Choose a path.
print("Lucky six!")Only shows when the dice gives 6.

RUN IT

Roll PyBot's dice.

Guess first. Then run real Python and check.

1

Guess the result

import random dice = random.randint(1, 6) print("You rolled", dice)

Which result can NOT appear?

dice.pyREAL PYTHON
OUTPUT
Ready. Press Run Python.
Python runs here thanks to Pyodide โ™ฅ

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

Surprise questions.

Try each tiny question. A wrong answer becomes something to review.

0Completed
9Not tried
0Review
01

Who goes first?

Ana and Leo want a fair way to decide who goes first in a game.

Which way is random?

02

The forgotten toolbox

dice = random.randint(1, 6) print(dice)

PyBot forgot the first line. What happens?

03

Which numbers?

random.randint(1, 3)

Which numbers can it give back?

04

Heads or tails

Which line flips a coin?

05

A pet from the hat

pets = ["cat", "dog", "fish"] print(random.choice(pets))

What can it show?

06

Run it again

You run a dice program twice. Do you always get the same number?

07

Three rolls

for turn in range(3): print(random.randint(1, 6))

How many numbers does it show?

08

Fix PyBot's code

PyBot wants to pick a snack at random, but it forgot the toolbox. Make it show: Yummy!

Goal output
Yummy!
OUTPUT

Your work is saved here.

Want a fresh start? Clear only this page.

!
BIG IDEA

random gives surprises.

Write import random once, at the top. Then randint picks a number and choice picks from a list. Each run can be different.