Python Random Number With Examples

In this tutorial, we are going to learn about Python Random Number. In our previous tutorial, we learned about Python math module.

Python Random Number

To work with python random number, we need to import Python’s random module at first. Python random module provides pseudo-randomness.

Python random module uses Mersenne Twister as the core random generator. So, this module is completely unsuitable for cryptographic purposes for being deterministic. However, we can use Python’s random module for most of the cases because Python’s random module contains many well known random distributions.

Python Random Integer

In this section, we will be discussing about generation integer numbers randomly. We can use randint(a,b) function to get a random integer from range a to b. Again, we can get number from a sequence by using randrange(start, stop, step) function. Let’s see an example to get python random integer.

For each run, the output will change. However, here given a sample output.

python-random-number

Python Random Float

There are several functions that returns real number or float randomly. For example, random() function returns a real number from 0 to 1 (exclusive).

Again, uniform(a, b) functions return a real number from a to b. Moreover there are some random distributions also available in Python random module. We can also get real number from those distribution.

We can get random numbers from exponential distribution by using expovariate(lambd) function.

The values in output will vary for each execution. You will get output like this.

Python Random seed

Python random number generation is based on the previous number, so using system time is a great way to ensure that every time our program runs, it generates different numbers.

We can use python random seed() function to set the initial value. Note that if our seed value doesn’t change in each execution, we will get same sequence of numbers. Below is a sample program to prove this theory about seed value.

Below image shows the output produced by the python random seed example program. We will get the same sequence of random numbers for each run.

python-random-number

Python Random List – choice(), shuffle(), sample()

There are some functions to use randomness in a sequence. For example, using choice() function you can get a random element from a sequence.

Again, using shuffle() function you can shuffle the elements in a sequence.

Also, using sample() function you can get x number of elements from a sequence randomly. So, let’s see the following code for random list example.

You may get output like the following.

So, that’s all for python random number. To know more, see their official documentation.

By admin

Leave a Reply

%d bloggers like this: