Experiments with Randomness


Random Numbers

Python's built-in random module defines a boatload of functions for working with random numbers. They are not truly random, so are often called pseudorandom numbers. However, they behave sufficiently like random numbers so we are able to use them effectively in many different settings.

For our needs this semester, we will just use two functions from the random module:

You can use a longer form of the import command to make these functions available directly:

    from random import randint
    die_1 = randint(1,6)

    from random import random
    game_result = random()

Compare to:
    >>> import random
    >>> random.randint(1, 6)
    6
    >>> random.randint(1, 6)
    3


 1. Suppose you wanted to simulate a dice game:

     die_1 = randint(1, 6)
     die_2 = randint(1, 6)
     diceTotal = die_1 + die_2
     if die_1 == die_2:
         print("You got doubles!")

 2.  Suppose you wanted to randomly pick a day of the year.

     day = randint(1, 365)

 3.  Note that we don't need randint() and could use random()
     to get the same range of random integers:
 
         die_1 = int( 6 * random() + 1 )
         die_2 = int( random() * 6 ) + 1

         day = int( 365 * random() + 1 )