fbpx

The Random Object

How can we create randomness in our programs?

There will be some instances where we want to generate some form of random values in our code, usually if we are running some sort of simulation. The built-in Random object provides us with a number of different helpful functions that help accomplish this, that we will dive into deeper as you work through future lessons.

An object (or a module) in Python is an instance of a class, and a class is a blueprint for creating objects. In other words, an object is a container that holds data (attributes) and functions (methods) that operate on that data. There are a number of built-in objects to the Python language (like Random), and in order to access its data and functions, we simply need to include an “import” statement, typically at the top of the document.

				
					# The following line of code allows us to access the random object
import random
				
			

The Random class contains a number of useful functions (found here) that you might consider using, but for now we will introduce a few functions to help accomplish basic tasks. We can access these functions by calling them using the syntax random.[function name goes here]

The randint Function

In order to generate a random number within a specified range, we can use the randint function. It takes in two inputs, or “parameters”, representing the lower and upper bound of the value you want to generate. 

For example, to simulate a random dice roll, we could use the following code:

				
					import random

# generate and store a random value between 1 and 6:
roll = random.randint(1, 6)

print("You rolled a", roll)
				
			

Try copying the code and running it in a Python file. You’ll notice that each time you do, the value of roll will change.

The randrange Function

The randrange function is almost identical to the randint function, but allows us to optionally specify a “step” between values. Additionally, the upper bound that we specify will be excluded from the possible outputs (whereas it was included in the randint function). For instance, if I wanted to generate a random even number from 0 to 10, I could use the following code:

				
					import random

# generate and store a random even number
num = random.randrange(0, 12, 2)

print("Your number is", num)
				
			

Notice that the step parameter is optional and placed at the end of the function call (we used 2 to limit the value to even numbers). Also, because the upper bound is exclusive of the value we specify, we set it to 12 in this case so that we can include the value 10 in our possible outputs.

Other Useful Functions

There are several other useful functions in the Random object that we will utilize a bit later on, such as choice(), shuffle(), and sample(). We will see how these can help us generate randomness within lists, which come up in module 2.

Replit Practice

Loading...