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.
Table of Content
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:
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.
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
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
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
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
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
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
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
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
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
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.
Example
import random
Output
import random
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:
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:
Also, note that the secrets module is available from Python 3.6 not in the below versions.
Example
import random
Output
import random
The second method is to call the SystemRandom() class’s random() method.
Example
import random
Output
import random
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
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.
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.
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.
It resets the current state of the generator to the input state object. You can fetch the same by calling the random.getstate() function.
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.
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
Example
import random
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.
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 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.
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.
import random
Output
import random
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.
The logic is pretty simple.
import random
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
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