using the random library

motivation

Sometimes we want to include some randomness in our programs. Examples include:

python includes a random library that you can import into your programs and use to generate random numbers or choices. The actual numbers are pseudo-random, meaning they are not really random. For our purposes (simple games), they are random enough.

syntax

First import the random library:

from random import *

Then use one of the various functions in the library. The most commonly-used functions are:

choice(seq) -- choose one from a sequence
randrange(start,stop) -- chose a random number from [start,stop-1]
shuffle(list) -- shuffles a list
random() -- returns a random float from [0,1)

examples

To simulate flipping a coin, you could use any of these:

flip = choice("HT")
flip = choice(["heads","tails"])
flip = randrange(2)    # assume 0 is heads, 1 is tails
flip = random()        # assume < 0.5 is heads

For example:

>>> from random import *
>>> for i in range(10):
...   flip = choice(["heads","tails"])
...   print(flip)
... 
tails
heads
tails
heads
heads
heads
heads
tails
tails
tails

To simulate rolling 6-sided dice:

result = randrange(1,7)

To shuffle a list:

>>> L = list("ABCDEFG")
>>> print(L)
['A', 'B', 'C', 'D', 'E', 'F', 'G']
>>> shuffle(L)
>>> print(L)
['E', 'B', 'C', 'G', 'F', 'A', 'D']
>>> shuffle(L)
>>> print(L)
['G', 'B', 'D', 'A', 'F', 'E', 'C']

challenge

Write a function called flip(n) that simulates flipping a coin n times. Your function should return the number of "heads" flipped.

$ python flipNcoins.py 
n: 100
Number of heads flipped: 52

CS21 Topics