A random number is the outcome of a process which arbitrarily chooses it from a sequence. It is called random number generation. With Python random module, we can generate random numbers to fulfill different programming needs. It has a no. of functions like randint(), random(), choice(), uniform() that as a programmer we can decide to use depending on the use case.

At the core, Python uses a Mersenne Twister algorithm, a pseudo-random generator (PRNG) to generate pseudo-random numbers. Its ability to produce uniform results makes it suitable for many applications. Knowing this fact is essential as it would help us determine when to use it and where not.

Studies reveal that PRNGs are suitable for applications such as simulation and modeling but not recommended for cryptographic purposes. And the same rule applies for the Python random number generator. However, we can use it for programming tasks like generating random integers between a range, randomly select an item from a list or shuffle a sequence in place.

Let’s now check out how to use the Python Random Module and see different functions to generate random numbers.

Generate Random Numbers in Python

Table of Content

  • 1 How to call random module in Python
  • 2 Generate a random number from a range
    2.1 randrange(stop)2.2 randrange(start, stop [, step])2.3 random.randint(low, high)* 3 Choose a random value from a sequence
    3.1 random.choice(seq)3.2 random.shuffle(list)3.3 random.sample(collection, random list length)* 4 Generate a floating point random number
    4.1 random.random()4.2 random.seed()4.3 random.uniform(lower, upper)4.4 random.triangular(low, high, mode)* 5 How to generate a secure random number?
    5.1 Python 3.6 secrets module5.2 SystemRandom() class random() method5.3 Directly call the os.urandom()5.4 Convert random bytes into a number* 6 State of random number generator in Python
    6.1 random.getstate()6.2 random.setstate(state)6.3 How to call getstate()/setstate()* 7 Using NumPy for random number arrays
    7.1 Get a random multi-dimension array of integers7.2 Choose a random value from a sequence* 8 How to generate a universal random number
    8.1 What is UUID?8.2 Python UUID module8.3 Why use UUID?8.4 Example* 9 Exercise – Guess the number game using random module
    9.1 Logic/Steps9.2 Sample code9.3 Output### How to call random module in Python

The Python Random module provides a range of functions to generate random numbers. So the first thing you should be doing is that import this module in your Python script.

import random

Or, you can also try the following syntax.

import random

Next, let’s see what you need to do for using the random module.

import random

Whenever you run the above piece of code, it’ll give you different output. Below is the one that we saw after executing at our end.

import random

Now, you should note the following points from the above example:

  • The code is calling the random() which is the most obvious function for random number generation.
  • It is one of the pre-requisites for most of the methods in the Random module.
  • By default, the random() function generates a float number between 0.0 and 1.0.

Now, we have divided the random number generation into three categories. Each category has some functions to produce desired random values in Python. Let’s check out.

Generate a random number from a range

randrange(stop)

It will produce a random integer value less than the value specified by the [stop] argument.

If “r” is a random number, then its value will lie in the range 0 <= r < stop.

import random

You can’t pass zero or negative value or a floating point number to this function as it’ll throw the ValueError exception.

Please see the below example.

import random

Output

import random

randrange(start, stop [, step])

It uses the following range [start, stop-1] to return a uniquely selected integer value. If the [step] is specified, then the randrange() output is incremented by it.

If “r” is a random number, then its value will lie in the range start <= r < stop.

import random

Example

import random

Output

import random

random.randint(low, high)

The randint() function is one of many methods that handle random numbers. It has two parameters low and high and generates an integer between low and high (including both).

Example

import random

Output

import random

Choose a random value from a sequence

random.choice(seq)

The choice() function arbitrarily determines an element from the given sequence.

Note– A sequence in Python is the generic term for an ordered set like a list, tuple, etc.

Examples

import random

random.shuffle(list)

The shuffle() function rearranges the items of a list in place so that they occur in a random order.

For shuffling, it uses the Fisher-Yates algorithm which has O(n) complexity. It starts by iterating the last element in the array to the first entry, then swap each entry with a value at a random index below it.

Example

import random

Output

import random

random.sample(collection, random list length)

The sample() function randomly selects N items from a given collection (list, tuple, string, dictionary, set) and returns them as a list.

It works by sampling the items without replacement. It means a single element from the sequence can appear in the resultant list at most once.

Example

import random

Output

import random

Generate a floating point random number

random.random()

It selects the next random floating point number from the range [0.0, 1.0]. It is a semi-open range as the random function will always return a decimal value which is less than its upper bound. However, it may return 0.

Example

import random

Output

import random

random.seed()

The seed() function performs the initialization of the pseudorandom number generator (PRNG) in Python.

It sets up the seed value which acts as a base to produce a random number. If you don’t provide a seed value, then Python uses the system current time internally.

Example

import random

Output:

import random

random.uniform(lower, upper)

It is an extension of the random() function. In this, you can specify the lower and upper bounds to generate a random number other than the ones between 0 and 1.

Example-1

import random

Output

import random

Example-2

import random

Output

import random

random.triangular(low, high, mode)

This function generates a float type random number FRN satisfying the below condition:

import random

Please note a few points before calling the triangular() method.

  • If you don’t specify any of low, high, and mode, then Python takes their values as ZERO, ONE, and the median of the first two values for the MODE.
  • It basically does a symmetric distribution.

Example

import random

Output

import random

How to generate a secure random number?

We have said at the beginning of this tutorial that PRNGs are not secure by default. So, it is a question mark so far that how do we generate a crypto-safe random number.

A crypto-safe random number is an ideal candidate for cryptographic applications. The data integrity remains critical in such software.

There are three ways in Python to generate a secure random value:

Python 3.6 secrets module

First, Python 3.6 introduced a module namely Secrets. It defines functions that can produce cryptographically secure random output. They act under the following conditions:

  • The secrets module has methods that generate a sequence of bytes instead of a single integer/float value.
  • The output quality will vary depending on the OS of the target machine.

Also, note that the secrets module is available from Python 3.6 not in the below versions.

Example

import random

Output

import random

SystemRandom() class random() method

The second method is to call the SystemRandom() class’s random() method.

Example

import random

Output

import random

Directly call the os.urandom()

Finally, you can directly call the os.urandom() method. The SystemRandom() class also uses this approach internally.

It returns a byte string of the specified size useful for the cryptographic purpose.

Example

import random

Output

import random

Convert random bytes into a number

Two of the above methods provide random bytes instead of an integer value. We can use the binascii module to convert the binary output into an integer value.

Check the below example.

Example

import random

Output

import random

In the above case, we used the hexlify() function which converts the bytes into an actual random number output. Also, you would have noted that we ran two iterations to show that each gives a different value.

One more point, the above code uses “iter” as a global variable to distinguish between two calls to the main(). Hope, you knew the below fact.

Note: Global variables in Python are accessible without declaring as global. But it is mandatory to do so for changing their values.

State of random number generator in Python

The random module includes the following two functions to manage the state of the random number generator. Once the state is available, you can use it to reproduce the same random value.

random.getstate()

It returns an object carrying the current state of the random generator. You can call the setstate() method with this value to restore the state at any point in time.

Note: By resetting the state, you force the generators to give the same random number again. You should exercise this feature only when needed.

random.setstate(state)

It resets the current state of the generator to the input state object. You can fetch the same by calling the random.getstate() function.

How to call getstate()/setstate()

If you save the last state and reset it, then it is possible to regenerate the same random number. However, if you change any of the random functions or their parameters, then it will break the logic.

Check out the below sampling example and see how the get/set methods impact the random number generation.

import random

Output

import random

It is clear from the summary that resetting the state makes the generator return the same sample list in consecutive attempts.

Using NumPy for random number arrays

NumPy is a scientific computing module in Python. It provides functions to generate multi-dimension arrays.

Since this module isn’t available in Python by default, so you need to pip it first by running:

import random

Get a random multi-dimension array of integers

  • Call random.random_integers(start, stop, size) to generate a 1-d array of random integer numbers between a range
  • Call random.random_integers(start, stop, size=(x, y)) to generate a n-d array of random values between [start, stop]

Example

import random

Choose a random value from a sequence

The numpy module provides the random.choice() method for choosing a random number from the sample list. We can utilize it to select one or more random values from a multi-dimension array.

Example

import random

Output

import random

To learn more variations on randomization using NumPy, check out this post: Generate Floating Point Random Numbers

It covers how you can generate a floating point random number as well as the array of floats using NumPy.

How to generate a universal random number

What is UUID?

A UUID (Universal Unique Identifier) is a 128-bit long number assigned to an object or entity for unique identification. As per specifications, it is quite unlikely that you can regenerate the same UUID.

Python UUID module

Python has a built-in UUID module which generates immutable UUID (Universally Unique Identifier) objects.

All functions in the UUID module are compatible with the available versions of UUID. If you like to generate a cryptographically secure random UUID, then uuid.uuid4() is the recommended function.

Why use UUID?

With the help of a unique identifier, it is easy to locate a specific document or user or resources or any information in a database or computer system.

Example

import random

Output

import random

Exercise – Guess the number game using random module

Dear all, you would have come to the end of this Python random generation guide. Hence, now is the time to test what you have learned from this tutorial.

Your exercise here is to code a famous ‘Guess the Number’ game by using a function from the Python random module.

We are providing our implementation of this game. We used the random.randint(start, stop) to generate a random answer.

Logic/Steps

The logic is pretty simple.

  • First, you generate a random answer from a specified range by calling a method from the Random module.
  • You also set the max number of attempts for the user to limit the retries.
  • Run a loop, ask the user to enter his choice, count his attempts.
  • Test the input value, if it matches, then stops and greet the user.
  • Otherwise, increment the attempts, let the user try until he exceeds the max tries.
  • If the user fails to guess the right number, then exit from the loop and display the sorry message.

Sample code

import random

Output

There are two outcomes of the ‘Guess the Numer’ game.

Success – You guessed the right number. Here, the less are your retakes, the better you performed.

import random

Failure – You couldn’t guess and exceeded the max attempts.

import random

Summary – Generate Random Numbers in Python

We’ve tried to portray the use of the Python random module and its functions in a simplified manner. Our purpose was to make it utterly simple so that even a newbie could understand it easily.

In this tutorial, we covered the most commonly used Python functions to generate random numbers. However, the Python random module also provides methods for advanced random distributions. These include Exponential, Gamma, Gauss, Lognormal, and Pareto distributions.

#python

Python Random Number Generator – A Step by Step Guide
2 Likes42.10 GEEK