Let's Get Random

There are many times when writing games or other programs when you're going to want to generate a random choice (it could be a random number or even a random element from a list). For example, in our Simon Says game, we're going to want to generate a sequence of random LED flashes as part of our game. As another example, imagine you want to create sports video game, where you are playing against the computer. If the opposing team ran the same exact plays in the same order every time you played the game, the game would get pretty boring.

Python provides a set of functions in the random module that can return random numbers. We'll describe the most common and useful functions below...

RandRange()

One of the simplest random functions is randrange(stop). It returns a random number grater than or equal to 0, but less than stop.

For example, if you try:

You might get:

0
3
3
2

Of course, if you run the program again (or many times), you'll almost certainly get a different set of numbers.

RandInt()

Another convenient function is randint(a, b). It returns a random number between a and b (it's inclusive, meaning the returned value could include a or b).

For example:

Might generate:

6
8
5
5

In this example, the return value will always be either 5, 6, 7 or 8.

Choice()

One more useful function is choice(x). It returns a random item in the list that you give it (where the list is x).

For example:

Might return:

tomato
kumquat
durian
kiwi
tomato