Sample code

In the code you copied over from my public/cs21/week06 is a file
To use the random library, you need to import it. At the top of your program:

from random import *You can also run help(random) in the python interpreter to see which functions the random library provides:

$ python >>> import random >>> help(random)The code in randomOps.py contains examples of how to use the most useful functions in this library:

random(): get the next random number in the range [0.0, 1.0) randrange(start, stop): get the next random number in the range [start, stop) randrange(stop): get the next random number in the range [0, stop)randomOps.py:

""" Some sample code illustrating use of random library Author: Andrew Danner Date: October 2008 """ from random import * def coinFlip(): """ Flip a coin randomly and return 'H' for heads or 'T' for tails returns: 'H' for heads or 'T' for tails """ if randrange(2)==0: return 'H' return 'T' ############################################################ def main(): #get a list of 5 random ints between 0 and 9 (inclusive) l=[] for i in range(5): rnum=randrange(10) l.append(rnum) print l #get a list of 3 random floats between 0 and 1 flist=[] for i in range(3): rfloat=random() flist.append(rfloat) print flist #flip a coin 4 times for i in range(4): print coinFlip(), print main()