# using the random library

Try the Jupyter notebook version.

## motivation

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

• games, where the computer makes a guess or a choice (e.g., rock, paper, scissors)
• simulations, where the outcome is random (e.g., flipping a coin, or rolling dice)

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 = 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):
...   print(flip)
...
tails
tails
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.

``````\$ python3 flipNcoins.py
n: 100