Dice, Coins and Fortune Cookies

Dice, Coins and Fortune Cookies: Python for Kids lesson banner with Beep and Pixel

Track: Python for Kids  ·  Lesson 9 of 10  ·  Ages: 8+  ·  Time: 35 minutes

Games are more fun when you cannot be sure what will happen. When you roll a dice, nobody knows which number will come up. Python can do the same. Today you will make a dice, a coin and a fortune-cookie machine, all from the random idea.

Beep says I love surprises! When I cannot decide between two snacks, I flip a coin. Now I can make Python flip it for me. Beep boop!

What you need

  • Python and IDLE.
  • A new file called lucky.py.

Grown-ups Because these programs use random numbers, their output is different every run, so expect your child’s output to differ from the examples shown. That is the whole point! Computers do not really flip coins. They use a clever recipe that makes numbers that look random. This is called pseudo-random, and it is more than good enough for games.

Borrowing the random tools

Python comes with a box of extra tools called modules. One of them is random. To use it, we write import random at the top of the program, which means “bring the random tools in”.

Here is a dice roller. The function random.randint(1, 6) picks a whole number from 1 up to 6, and, unlike range, it includes both ends.

import random

roll = random.randint(1, 6)
print("You rolled a", roll)

Your output might look like this, or it might show any number from 1 to 6:

You rolled a 4

Run it again and again. You will see a different number from time to time. The word randint is short for “random integer”.

Pixel says Every number from 1 to 6 has the same chance. Rolling a 6 three times in a row can happen, but it is rare. Meow!

Rolling lots of times

Put the roll inside a loop to roll again and again:

import random

for roll_number in range(5):
    roll = random.randint(1, 6)
    print("Roll", roll_number + 1, "was a", roll)

Here is one possible result:

Roll 1 was a 3
Roll 2 was a 6
Roll 3 was a 1
Roll 4 was a 6
Roll 5 was a 2

Notice that the roll numbers always go 1 to 5 in order, but the dice values change every time you run it.

Choosing from a list

What if you want to pick a random word instead of a number? Use random.choice, which picks one item from a list. A coin has two sides, so here is a coin flip:

import random

coin = random.choice(["heads", "tails"])
print("The coin landed on", coin)
The coin landed on tails

Beat the robot!

Let us mix randomness with decisions from lesson 5. You and Beep each roll a dice, and the highest number wins:

import random

your_roll = random.randint(1, 6)
robot_roll = random.randint(1, 6)
print("You rolled", your_roll)
print("Beep rolled", robot_roll)
if your_roll > robot_roll:
    print("You win! Hooray!")
elif your_roll < robot_roll:
    print("Beep wins! Beep boop!")
else:
    print("It is a tie!")

One possible game:

You rolled 5
Beep rolled 2
You win! Hooray!

Because the dice are random, you can play it over and over, and sometimes you will win and sometimes Beep will.

The fortune cookie machine

Now for the best bit. We make a list of fortunes, and the computer picks one at random. We will also add a lucky number.

import random

fortunes = [
    "A big adventure is coming your way.",
    "You will soon have a very good idea.",
    "Today is a great day to learn something new.",
    "A friendly cat will make you smile.",
    "Your next program will work the first time.",
]

print("Cracking open your cookie...")
print("Your fortune:", random.choice(fortunes))
print("Your lucky number is", random.randint(1, 99))

The first line always says the same thing, and the other two change every time:

Cracking open your cookie...
Your fortune: A friendly cat will make you smile.
Your lucky number is 42

You can ask the robot a question too. This silly Magic Beep ball listens to your question and then picks an answer from the list. The answer has nothing to do with the question!

import random

answers = ["Yes!", "No way!", "Ask again later.", "Definitely!", "Maybe..."]
question = input("Ask Magic Beep a yes or no question: ")
print("You asked:", question)
print("Magic Beep says:", random.choice(answers))
Ask Magic Beep a yes or no question: Will Pixel nap today?
You asked: Will Pixel nap today?
Magic Beep says: Definitely!

Random colours: a confetti picture

Random works in drawings too. This program scatters 40 coloured dots in random places and random sizes. The picture below is only one example, because yours will look different every time.

import turtle
import random

t = turtle.Turtle()
t.penup()
t.hideturtle()
colours = ["red", "orange", "gold", "green", "blue", "purple", "hotpink"]
for dot in range(40):
    t.goto(random.randint(-150, 150), random.randint(-150, 150))
    t.dot(random.randint(10, 30), random.choice(colours))

turtle.done()
The drawing made by the turtle code above
This is what the code above draws.

The line t.penup() lifts the pen so the turtle does not draw lines as it jumps around, and t.dot(size, colour) puts a filled dot where the turtle is.

Did you know? Computers use random numbers all over the place: in video games to decide what a monster does next, in music players to shuffle songs, and in science to test ideas that depend on chance.

Challenges

Try it Change the dice to roll two dice and print their total. What is the smallest total you can get? What is the biggest?

Show the answer
import random

first = random.randint(1, 6)
second = random.randint(1, 6)
print("You rolled", first, "and", second)
print("Total:", first + second)

The smallest total is 1 + 1 = 2 and the biggest is 6 + 6 = 12. You can never get a total of 1 with two dice!

Try it Write a “pick a snack” program with a list of at least four snacks. Use random.choice to tell Pixel what to eat for a treat.

Show the answer
import random

snacks = ["a fish biscuit", "an apple", "some popcorn", "a banana"]
print("Pixel will have", random.choice(snacks))

Try it Make a 20-sided dice game: roll random.randint(1, 20) and print “Critical hit!” if the roll is 20, “Good shot!” if it is 10 or more, and “Oh dear, a miss.” otherwise.

Show the answer
import random

roll = random.randint(1, 20)
print("You rolled", roll)
if roll == 20:
    print("Critical hit!")
elif roll >= 10:
    print("Good shot!")
else:
    print("Oh dear, a miss.")

What you learned

  • import random brings in Python’s random tools.
  • random.randint(1, 6) picks a random whole number, including both ends.
  • random.choice(a_list) picks one random item from a list.
  • Programs that use random produce different results each time you run them.
  • You can combine random with if, loops and lists to build games.