Using the random library

Random thoughts on random libraries

Sometimes we want the computer to pick a random number in a given range, pick a random element from a list, pick a random card from a deck, flip a coin, etc. The random module provides access to functions that support these types of operations. The random module is another library of functions that can extend the basic features of python. Other modules we have seen so far are string, math, time and graphics. With the exception of the graphics module, all of these modules are built into python. For a full list of python modules, see the online documentation listing all of the default modules. To get access to the random module, we add from random import * to the top of our program (or type it into the python shell).

Open the file randOps.py in vim, and run the program in a separate terminal. Note if you run the program again, you get different (random) results. This program illustrates the functions randrange and random. We will most often be using randrange. This function generates a list just like range, but then returns one item randomly from that list.

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()