Lab10 - Programming your own classes
In this lab we will get some practice in writing classes and using Python's random number generator.
The Die class
Write a class called Die that can simulate the rolling of a single die. Your class should have the following methods and attributes:
- A constructor that takes two parameters: num_faces: the number of faces of the die (default should be six, and your code should check that when this is provided, it is an integer whose value is greater or equal to 4) and seed: the seed for initializing the random number generator. The default is having no seed.
- The
Dieclass should have instance variables callednum_facesandroll_valuewhich store the number of faces and the current value rolled. The roll_value should be initialized toNonewhen an instance is first created. - A
roll()method that rolls the die and returns the value that was rolled. The value is stored in theroll_valueattribute. To roll the die use therandom.randrangemethod. See below for details on using the Python random number generator. - A
__repr__()method that returns a useful string representation of the current state of the object.
Create a list of the result of rolling a 10-faced die 10000 times and compute the fraction of times each value was rolled.
Random numbers in Python
Here are a few Python commands that will need for implementing your Die class:
import random
random.seed(10)
# or random.seed(None) if you don't want to set a seed
print random.randrange(1, 7)
# generate a random number between 1 and 6
random.seed(10)
# or random.seed(None) if you don't want to set a seed
print random.randrange(1, 7)
# generate a random number between 1 and 6
More details on the Python random number generator can be found in the library documentation.
