Random Number Generator in Python

Filed Under: Python

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.


>>> from random import randint
>>> 
>>> randint(1, 10)
6
>>> randint(1, 10)
8
>>> randint(1, 10)
2

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.


>>> from random import randrange
>>> 
>>> randrange(1, 10)
8
>>>

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).


>>> import random
>>> 
>>> random.random()
0.5453202789895193
>>> random.random()
0.9264563336754832
>>> 

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.


>>> random.random() * 100
28.226855764270553
>>> random.random() * 100
41.844280268733115
>>>

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.


>>> from random import choice
>>> nums = [1,3,5,7,9,11]
>>> choice(nums)
5
>>> choice(nums)
7
>>> choice(nums)
3
>>> choice(nums)
3
>>> 

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.


>>> import random
>>> 
>>> random.seed(1000)
>>> 
>>> random.random()
0.7773566427005639
>>> random.random()
0.6698255595592497
>>> random.random()
0.09913960392481702
>>> 
>>> random.seed(1000)  # resetting the seed again to 1000
>>> 
>>> random.random()
0.7773566427005639
>>> random.random()
0.6698255595592497
>>> random.random()
0.09913960392481702
>>> 

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages