# 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 a 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 greater than or equal to 0, but less than stop.

For example, if you try:

from random import randrange print(randrange(5)) print(randrange(5)) print(randrange(5)) print(randrange(5))

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:

from random import randint print(randint(5, 8)) print(randint(5, 8)) print(randint(5, 8)) print(randint(5, 8))

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:

from random import choice my_favorite_fruits = ['kumquat', 'mango', 'durian', 'kiwi', 'tomato'] print(choice(my_favorite_fruits)) print(choice(my_favorite_fruits)) print(choice(my_favorite_fruits)) print(choice(my_favorite_fruits)) print(choice(my_favorite_fruits))

Might return:

    tomato
    kumquat
    durian
    kiwi
    tomato