Python Random

Python can make random numbers.

Normally you only have access to Python’s built in functions, but there are many modules that have more useful functions.

Python’s random module gives you access to many functions related to generating random numbers.

First you need to import the random module.

Make this the first line of your program:

import random

Now you can run functions from the random module.

Example 1: random number between 0 and 1

x = random.random()
print(x)

This can be used in various other ways:

#random decimal number between 0 and 100
a = random.random() * 100

#random decimal number between 5 and 6
b = random.random() + 5

You can also use random.random() to give something a percentage chance of happening:

if random.random() < 0.25:
    print("You win!")
else:
    print("Sorry, you lose.")

That example “wins” 25% of the time, since 25% of the numbers between 0 and 1 are less than 0.25.

Example 2: random integer in a given range:

x = random.randint(4, 7)
print(x)

That will give a random integer from 4 to 7, which could include both 4 and 7.

Example 3: random item from a list:

my_list = ['apple', 'orange', 'airplane', 'carrot']
thing = random.choice(my_list)
print(thing)

This example randomly prints one of the strings in my_list.

Instead of a list, you could also  choose a random item from a different type of collection, such as a string or tuple.

random_letter = random.choice("abcdefghikj")

random_prime = random.choice( (2, 3, 5, 7, 11) )