Generate Random Numbers in Python Using Random Module

Generate Random Numbers in Python Using Random Module

Python Random Module – yes today we will talk about how to generate random numbers in python using the random module. This module has many functions to generate random numbers in different scenarios, which we will all cover in this tutorial.

Python random module uses a pseudo-random number generator function called random() and generates the random float number between 0.0 to 1.0. You can use this module in various cases like lottery systems, puzzles, and games, etc.

So let’s get started.

Import Random Module

The first thing you know is that you have to import the random module into your program file. After importing, you are ready to use this module.

To import the random module, use the following code line in your file.

Let’s see the basic example of the python random module.

Output:
0.6831919584731698

In the above example, you see we use the most basic function (random.random()) of the random module. It generates the random number 0.6831919584731698 for me but it may be different when you try this code.

As we said earlier, it will generate random numbers between the default range of the function is 0.0 to 1.0 that’s why we have got 0.68.

Random module functions

Python random module has many functions to generate the random numbers including integer and float. You can also generate the random number between the range or select the random number from the python sequence.

Recommend tutorial: Python Sequences – Types, Operations and Functions

See the following list of the random module functions.

  • random.seed(a=None, version=2): Initialize the random number generator.
  • random.randrange(start, stop[, step]): Generate the random integer number between the range and using the step increment.
  • randint(a, b): Return the random integer number from a to b range.
  • random.choice(seq): Select the random item from the sequence.
  • random.choices(population, weights=None, *, cum_weights=None, k=1): Return a k sized list of elements chosen from the population with replacement
  • random.sample(population, k, *, counts=None): Return a k length list of unique elements chosen from the population sequence.
  • random.shuffle(x[, random]): Shuffle the sequence x in place.
  • random.uniform(start, end): Generate the float random number.
  • random.triangular(low, high, mode): Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds.

So these are the main functions of the random module to generate the random number. The number could be integer or float. We can also select the random item from the sequence of a set by using some of these functions.

Generate Random Number Using the Random Module Functions

So as we see a short summary list of random module functions, now let’s have a look at them one by one with an example.

random.seed()

The random.seed() function is used to generate the random numbers by using the seed value. The seed value is a base value that is used by a pseudo-random generator. In computer security, the seed value is important for pseudo-randomly generating a safe secret encryption key.

Syntax:

Parameters:

There are two parameters and both are optional.

a: If a is none then random.seed() function uses the current system time by default. If randomness sources are provided by the operating system, they are used instead of the system time. And if the value of a is integer then it will use directly.

version: If the default version 2 is provided then str, bytes, and bytearray object gets converted into an integer, and all of its bits are used.

Let’s generate the random number using the random.seed() function of the random module.

Output:
17
17
17
17

Recommend tutorial: Python Range Function

 

random.randrange()

The random.randrange() function will generate the random integer between the specified range and using the increment parameter.

Syntax:

Parameters:

It takes three parameters. The start and step parameters are optional but you have to specify the stop parameter to generate the random integer number.

strat: It is the starting number of the range and the default value is 0. It is an optional parameter.

stop: It is the last number of the range. You must have pass this parameter in the function because it is a required parameter.

step: It is an incremental number while generating the random integer numbers. The default of this is 1.

Let’s have a look at the below example to generate the random integer using the random.randrange() random module’s function.

 

random.randint()

Using the random.randint() function of the random module, you can also generate the random integer number. You just have to specify the start and stop parameters.

Syntax:

Parameters:

It takes two parameters that are required. YOu have to pass the parameters while generating the random integer number.

start: It is the start number of a range and the default value is 0.

stop: It is the stop/end number of the range

 

random.choice(seq)

The random.choice() function is used to select the random item from the python sequence types (like list, dictionary, string, tuple, etc). Make sure the sequence is not empty and if it is empty then it will return the IndexError.

Syntax:

Parameters:

It has one parameter and it is required.

seq: It is the python sequence types like list, tuple, etc and it should be non-empty.

Output:
242

 

random.choices()

By using the random.choices() function, you can get the weighted random choice from the population. It will return the k sized list of items chosen from the population with replacement. If the population is empty then it will return the IndexError.

Syntax:

Parameters:

population: It is a data set of python sequences.

weights: If a weights sequence is specified, selections are made according to the relative weights.

cum_weights: if a cum_weights sequence is given, the selections are made according to the cumulative weights.

k: It is a number of samples that you want to select from the population.

Output
[68, 92, 92]

 

random.sample()

The random.sample() function is used to select multiple items from the python sequence types (like list, tuple, dictionary, etc). It will return a k length list of unique items chosen from the population sequence or set.

Syntax:

Parameters:

population: It is a sequence type like list, tuple, string, from which you will select items.

k: It is a number that how many you want to select from the sequence. It should be less than the size of the list items.

counts: You can specify the repeated items at once using the counts keyword. For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5).

Output
[456, 68]

 

random.shuffle()

It is used to shuffle the sequence in python. You can shuffle the items of the list, string, dictionary, etc. When you use this random.shuffle() function, it will change the order of list items. For example, you can use this function in the cubic game.

Syntax:

Parameters:

It takes the two parameters, one is required and the second is optional.

x: It refers to the sequence that we want to shuffle.

random: The optional parameter random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

Output
[13, 36, 68, 242, 92, 456]
[456, 13, 92, 68, 242, 36]

 

random.uniform()

The random.uniform() function generate the floating-point number within the range. The range could be normal like 50 to 70 or pointing 4.6 to 5.67.

Syntax:

Parameters:

start: It is the start a number of the python range and the default value will be 0.

end: It is the end number, which means the last number of the range.

Output
65.24308285079945
5.488308869793038

 

random.triangular()

The random.triangular() function returns a random floating-point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one.

Syntax:

Parameters:

low: It is the lower limit of the random number
high: It is the upper limit of the random number
mode: It is a number used to weigh the result in any direction.

Output
41.58710794642932

Conclusion

So in this tutorial, you learned about the python random module and how to import and use it. And how to generate random numbers using the random module in python. The python random module uses a pseudo-random number generator function called random() and generates the random float number between 0.0 to 1.0.

We also covered all the most common functions of a random module to generate the random number and select the random item from the list, tuple, dictionary, etc.

Hope you like it!

If you have any queries please let me know in the comment section, I’ll respond to you as soon as possible.

You May Also Like

About the Author: Aman Mehra

Hey! I'm Aman Mehra and I'm a full-stack developer and have 5+ years of experience. I love coding and help to people with this blog.

Leave a Reply

Your email address will not be published.