Random Number Generator in Python With Examples

We can use Python random module to generate random numbers. We can use this module to generate random integers, floating-point numbers, or a sequence of random numbers.

1. Generating Random Integer in Python

Python random module randint() function can generate a random number between the given endpoints.

Note that the randint() includes both endpoints while generating the random integer. If you don’t want the second endpoint to be included, then use randrange() function.

2. Generating Random Float in Python

The random module has range() function that generates a random floating-point number between 0 (inclusive) and 1 (exclusive).

There is no separate method to generate a floating-point number between a given range. For that, just multiply it with the desired range.

Here is a simple program to generate a random floating-point number between 0 and 100.

3. Chosing a Random Number from a Sequence

We can also use the random module to select a random number from a sequence using the choice() method.

4. A quick word on Random Seed

When we call random module functions, it initializes the Random class internally and uses the current system time to generate the seed value. This seed value is then used to generate random numbers.

We can also set the random seed, in that case, the same sequence of random numbers will get generated every time.

Let’s understand this behavior with a simple example.

Notice that the random numbers generated each time are following the same sequence. Unless you want something like this, try to avoid setting the random seed value.

By admin

Leave a Reply