Skip to content
Home » Random Numbers and the random Module in Python

Random Numbers and the random Module in Python

Spread the love

Today we’ll discuss some of the most used functions from the random module. They are used if you need random numbers or some other random results.

Here’s a video. Feel free to watch it:

To start off, we’ll import all the functions from the module, then we’ll have a look at the most important functions that return random numbers and finally we’ll have a look at some other interesting functions.

Random Numbers

random numbers

OK, so there are a couple of functions that return random numbers:

Random Float Numbers

Let’s import all the functions from the random module, because we’re going to need quite a few of them.

random

The first function is random. It returns a random float number between 0.0 and 1.0, the upper bound not being included. Here’s an example:

>>> from random import *

>>> random()
0.5989133362239941
>>> random()
0.9464900343580076
>>> random()
0.8071773032748506

Naturally these numbers are random, so you will get a different result each time and your results will differ from mine.

uniform

Another function that returns a random float number is uniform. This function returns a random floating point number between two arguments, x and y:

>>> uniform(4, 5)
4.530885214461829
>>> uniform(4, 5)
4.058963631529784
>>> uniform(4, 5)
4.937568572195356

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Random Integer Numbers

If you need a random integer number, there are a couple functions you can use.

randint

Let’s start with the randint function. It returns a random integer between two arguments, x and y, both x and y are included.

>>> randint(3, 10)
9
>>> randint(3, 10)
10
>>> randint(3, 10)
7

As with the float numbers before, you will get a different result each time.

randrange

Another function is randrange. It returns a random element from a range given by two arguments, x and y, the latter not being included:

>>> randrange(5, 8)  
5
>>> randrange(5, 8)
7
>>> randrange(5, 8)
6

You can also use this function with just one argument, which is the upper bound of the range. Then the lower bound defaults to 0:

>>> randrange(3)  
2
>>> randrange(3)
1
>>> randrange(3)
0

Besides the two arguments, x and y, you can also pass a third argument, the step:

>>> randrange(10, 1000, 50) # possible results are: 10, 60, 110, 160, etc.
960
>>> randrange(10, 1000, 50)
410
>>> randrange(10, 1000, 50)
660

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Other Functions in the random Module

And now some other functions from the random module:

shuffle

shuffle

This function rearranges all the elements of a list. Here’s an example of how you can use it:

from random import *

def who_ate_whom(animals):
    print("The {0} was eaten by the {1} and the {1} was eaten by the {2}.".format(*animals))

animals = ['fish', 'cat', 'snake']

# Let's play a WHO-ATE-WHOM game
who_ate_whom(animals)

# Let's shuffle the animals and play again
shuffle(animals)
who_ate_whom(animals)

# Let's try again
shuffle(animals)
who_ate_whom(animals)

# and again
shuffle(animals)
who_ate_whom(animals)

Output:

The fish was eaten by the cat and the cat was eaten by the snake.
The snake was eaten by the fish and the fish was eaten by the cat.
The cat was eaten by the fish and the fish was eaten by the snake.
The fish was eaten by the snake and the snake was eaten by the cat.

sample

sample

This function picks one or more random elements from a sequence or set:

from random import *

def menu(day, meals, num_of_courses):
    print(f"Menu for {day}:")
    current_menu = sample(meals, num_of_courses)
    for meal in current_menu:
        print(meal)
    print()

food = ['pasta', 'noodles', 'dumplings', 'pizza', 'hot-dogs', 'hamburgers']

# Let's see what's on the menu on Thursday
menu("Thursday", food, 2)   # pick 2 random elements from food

# How about Friday?
menu("Friday", food, 4)   # pick 4 random elements from food

# How about Saturday?
menu("Saturday", food, 1)   # pick 1 random element from food

Output:

Menu for Thursday:
noodles
hamburgers

Menu for Friday:
hamburgers
dumplings
pasta
hot-dogs

Menu for Saturday:
hot-dogs

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

choice

choice

This function returns one random item from a sequence:

from random import *
import time

def who(folks):
    print("Who's gonna clean the toilets today?")
    print("Well, let me think...")
    time.sleep(3)
    print("OK, I think I know...")
    time.sleep(2)
    loser = choice(folks)
    print(f"It's gonna be {loser.upper()}!")
    print()

students = ['John', 'Mike', 'Sue', 'Stella', 'Emily', 'George']

# Let's play the game to see who's gonna clean the toilets
who(students)

# Let's try again
who(students)

Output:

Who's gonna clean the toilets today?
Well, let me think...
OK, I think I know...
It's gonna be EMILY!

Who's gonna clean the toilets today?
Well, let me think...
OK, I think I know...
It's gonna be SUE!

Naturally there are other functions in the random module as well. Feel free to experiment with them.


Spread the love

Leave a Reply