How to generate random numbers in Python

Let’s say you need to generate random numbers in Python. I need it once for an application that generates random numbers in order to create math problems to be solved by students. But being able to generate random numbers is useful in many other situations. In order to generate random numbers in Python we need to import the random module.

If you just need a random number between 0.0 and 1.0 then just call random.random().

>>> import random
>>> random.random()
0.74002357942266106
>>> random.random()
0.07003308263110275
>>> random.random()
0.14104273470877104

You might want to generate numbers within a certain range. For that you have to import randint which stands for “random integer”.

,code>>>> from random import randint
>>> n1 = randint(1, 99)
>>> n2 = randint(1, 99)
>>> n3 = n1 + n2
>>> n1
9
>>> n2
47
>>> n3
56

Both n1 and n2 generate random integer between 1 and 99.

You can also make a random choice among a number of possibilities by using the random.choice().

import random
>>> numbers = [16, 6, 1977, 84, 5, 7, 2007]
>>> random.choice(numbers)
2007
>>> random.choice(numbers)
6
>>> random.choice(numbers)
16
>>> random.choice(numbers)
7

If you need then you can be very creative with the random module.

Leave a Reply