Please enable JavaScript to use CodeHS

Randomization in Python

Learn how to make programs more exciting through randomization!

By Evelyn Hunter

Randomization plays an important role in many applications like video games, physics modeling, cryptography, and even art and music! It allows us to simulate real world behavior, and better understand how certain processes work - for example, we can use random numbers to create a program to predict how different species might interact with one another in the wild!

We can use randomization in our programs by importing the random library. A library is a collection of functions and programs that have been created by others that can be used in other programs. To “use” a library, we first need to import the library into our own program. To do so, we simply need to include the line:

import random
Plain text

at the beginning of our program. This will import all of the functions from the random.py file so that they can be used in our program without any hassle. You can learn more about the random library from the Python documentation.

Random Functions

Once random is imported, we can take advantage of the different functions built in the random class. The two most useful functions from random that are used on CodeHS are randint and choice.

randint(low, high) returns a random integer between low and high inclusive:

import random

int num = random.randint(1,5)
print(num)    #prints a random number between 1 and 5, including both 1 and 5
Plain text

You’ll notice that in order to use a function from the random class, we have to use the keyword random before calling the function we want to use. This indicates that we are accessing a function directly from the random class, and not from our current file.

Practice

A board game company is creating a new lotto game where users press a button and get three numbers from 1-10. Write a program that gets three random numbers from 1-10 and prints them to the console.

Like randint, choice randomly chooses an element from a sequence of elements. It can be used on String sequences:

import random

element = random.choice("abcdefg")
print(element)  #prints one character from the String 'abcdefg'
Plain text

Or a list sequence:

import random

list_item = random.choice(["Merry", "Had", "A", "Little","Lamb"])
print(list_item)    #prints an index from the given list
Plain text


Practice

The game company you work for also wants to create an online version of Bingo. They’ve asked you to create a program that generates a random number from 1-99 and a letter from the sequence “BINGO”. The final value printed to the console should be in the form Letter - Number. For example, a valid Bingo key would be “B-52”. Try creating this program in the following exercise.