Page 36 - Programming the Raspberry Pi Getting Started with Python
P. 36
the loop, the next value of x will be printed out.
Simulating Dice
We’ll now build on what you just learned about loops to write a program that simulates throwing a die
10 times.
To do this, you will need to know how to generate a random number. So, first let’s work out how to
do that. If you didn’t have this book, one way to find out how to generate a random number would be
to type random numbers python into your search engine and look for fragments of code to type into
the Python Shell. However, you do have this book, so here is what you need to write:
Try entering the second line a few times, and you will see that you are getting different random
numbers between 1 and 6.
The first line imports a library that tells Python how to generate numbers. You will learn much
more about libraries later in this book, but for now you just need to know that we have to issue this
command before we can start using the randint command that actually gives us a random number.
NOTE I am being quite liberal with the use of the word command here. Strictly speaking, items
such as randint are actually functions, not commands, but we will come to this later.
Now that you can make a single random number, you need to combine this with your knowledge of
loops to print off 10 random numbers at a time. This is getting beyond what can sensibly be typed into
the Python Shell, so we will use the IDLE Editor.
You can either type in the examples from the text here or download all the Python examples used in
the book from the book’s website (www.raspberrypibook.com) . Each programming example has a
number. Thus, this program will be contained in the file 3_l_dice.py, which can be loaded into the
IDLE Editor.
At this stage, it is worth typing in the examples to help the concepts sink in. Open up a new IDLE
Editor window, type the following into it, and then save your work:
The first line begins with a # character. This indicates that the entire line is not program code at all,
but just a comment to anyone looking at the program. Comments like this provide a useful way of
adding extra information about a program into the program file, without interfering with the operation
of the program. In other words, Python will ignore any line that starts with #.
Now, from the Run menu, select Run Module. The result should look something like Figure 3-6,
where you can see the output in the Python Shell behind the Editor window.