Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

106 Chapter 6


The common element in these games is the idea of randomness.
We want the computer to pick a number at random between 1 and
10, and we guess what that number is. We want the computer to
randomly pick rock, paper, or scissors, and then we choose what
to play and see who wins. These examples—plus dice games, card
games, and so on—are called games of chance. When we roll five
dice to play Yahtzee, we usually get a different result every time
we roll. That element of chance is what makes these games fun.

We can program the computer to behave randomly. Python has
a module called random that allows us to simulate random choices.
We can use the random module to draw random shapes on the screen
and program games of chance. Let’s start with a guessing game.

A Guessing Game


We can use random numbers in the classic Hi-Lo guessing game.
One player picks a number between 1 and 10 (or 1 and 100), and
the other tries to guess the number. If the guess is too high, the
guesser tries a lower number. If they guessed too low, they try a
higher number. When they guess the right number, they win!
We already know how to compare numbers with the if state-
ment, and we know how to keep guessing using input() and a while
loop. The only new skill we need to learn is how to generate a ran-
dom number. We can do this with the random module.
First, we have to import the random module with the command
import random. You can try this in the Python shell by typing import
random and pressing enter. The module has a few different func-
tions for generating a random number. We’ll use randint(), short
for random integer. The randint() function expects us to give it
two arguments—that is, two pieces of information—between its
parentheses: the lowest and highest numbers we want. Specifying
Free download pdf