Write a program that simulates rolling dice. The most common physical dice have 6 faces, but there are also dice that have 4 faces, 8 faces, 10 faces, 12 faces, and 20 faces. Virtual dice simulated by a computer can have any number of faces, since they don't have to be physically constructed. You get to tell the program how many faces your die has each time you run it. You will use the random
module to generate pseudo-random numbers that represent rolling the die.
Objectives
- to give you familiarity with generating random numbers in Python
- to learn to use the randint function in the random module
- to reinforce importing of external modules and dot notation
Generating Random Numbers in Python
The random
module in the Python programming environment has a number of functions to generate random numbers. For example, the random.randint(a, b)
function can generate an integer random number in the range a
through b
(including a
and b
).
For example, every time you invoke randint(1, 6)
, it will return a random number between 1
and 6
(1 <= a <= 6
). We can call this function to simulate an action of rolling a die. In order to use this function, you need to import
the random
module, like this --
import random
# Now you can use the randint() function:
z = random.randint(1, 6)
# z contains a random integer number between 1 and 6
print("You rolled a die and it's value is:", z)
# You can roll the dice again:
z = random.randint(1, 6)
# Let's check what you've got this time
print("You rolled the die again and this time you've got:", z)
Now, we can use the same idea to simulate a dice with 8 faces.
import random
z = random.randint(1, 8)
print("You have rolled a die with 8 faces and you've got:", z)
Exercise
Write a program that takes the number of faces from the user, rolls the dice 5 times. Sum up those values and find the average of those values. Print the sum and the average at the end.
Your program should ask the user for the number of faces, like this:
How many faces does your die have? 8
and generate an output like this:
Your die has 8 faces
You have rolled it 5 times
The sum is: 26
The average is: 5.2
NOTE: In order to auto-grade your program, zyBooks needs to be able to predict what the "random" rolls of the die will be. This is done with the random.seed() function. When developing and testing your program, you can comment out the line with random.seed(1111) so that you will see "random" rolls. When you are ready to submit for testing, you must uncomment that line so that zyBooks will be able to predict, duplicate, and check the dice rolls.