generate random numbers in python

3 Mins Learn to Generate Python Random Numbers

The tutorial aims to help you learn how to generate Python random numbers in 3 minutes. The following article will show you two ways to generate random numbers in Python.

One is use build-in module random, another situation is use numpy.

These are the two most common ways that Python generates random numbers in our program projects.

Let’s get started!

Use build-in random module to generate random numbers

For example, if you want to generate a random number of 0 to 9, its code is as below:

from random import randint

print(randint(0, 9))

It is worth noting that, these are pseudo-random numbers and should not be used for security purposes.

For security or cryptographic uses, you can use secrets module, which is new in Python3.6, instead of the random module to generate strong numbers.

A code example of thesecrets module, as shown below:

from secrets import randbelow


Use numpy to generate random numbers

If you aspire to be a data analyst/data scientist, the use of numpy module is a necessary skill.

Using numpy module to generate random numbers code as shown below:

import numpy as np

print(np.random.randint(low=1, high=10, size=1)[0])

After running the commands above, you’ll get the random number of integers that you want.

Final conclusion

Random numbers are easy to generate. Please leave a message below, let me know if this was helpful and if you need any additional explanation.



Leave a Reply

Notify of