Marshall Brain’s Quick and Easy Python Tutorials – Chapter 5

by Marshall Brain

In the previous tutorial we simulated the process of flipping a coin. What if we want to simulate the idea of rolling dice? This program shows one way to do it:

This program does work. It rolls a simulated 6-sided dice 1,000 times and records how many times each face of the die comes up. It does this using six different variables called face1 through face6. But this is kind of a pain in the neck. And if we wanted top simulate the roll of a 20-sided dice, it really would be frustrating. What we need is a better way to think about groups of similar variables.

Fortunately, Python and most other computer languages will let you, the programmer, create arrays or lists of variables. An array gives you an easy way to solve the 6-sided dice problem, and even the 20-sided dice problem. This new program uses a Python list to replicate the previous program:

The line that says “face = []” tells Python that you want to create a list, but you do not know how big you want the list to be. An alternative would have been to say:

face = [0,0,0,0,0,0]

This would creat a list with 6 zeros in it. But we don’t want to do that, because we might want to simulate a 20-sided dice in the future. So we say, “face = []” to keep our options open. Python knows we want face to be a list, but it does not yet know how long the list will be.

The first for loop sets the size of the list by appending 6 zeros to it.

So now we have a list containing 6 elements. If we were to say “face[0]=5”, that would set the first element in the list to 5. If we were to say “face[2]=8”, that would set the third element in the list to 8. If we were to say “face[24]=7”, that would create an error because our list only has 6 elements in it. The number inside the square brackets is called the index into the list.

In the second for loop in our program we say “roll the dice with randrange, and then add one to that element of the list.”

Then in the third for loop we print out the number of times each face came up.

This little program can simulate 1,000 rolls of a 6-sided dice. You could easily change it to 10,000 or 1,000,000 rolls by changing the second for loop.

But even more exciting is that you can easily simulate a 20-sided dice by changing just the NumberOfFaces variable at the top of the program to 20. The program will change the size of the list and handle 20 faces instead. Try it!

When you compare the first program to the second program, you can see that a Python list makes life much easier for us. Lists can be as big as you like. If you wanted to simulate a 100 face dice, you could do that too, even though 100-face dice do not exist in reality.

See also: “I Need Practice Programming”: 49 Ideas for Game Clones to Code

<<< Go to Tutorial 4   |   Intro

Python Table of Contents

The Official Site for Marshall Brain