This post will discuss how to generate a random number in Python.

1. Using random.randrange() function

A simple approach to generate a random number between the specified range in Python is using the random.randrange() function. Here’s an example of its usage:

Download  Run Code

 
To generate a random element less than a value, you can use the following code:

Download  Run Code

2. Using random.randint() function

The random.randrange(x, y) function generates the random integer n such that x <= n < y. If you need to generate a random number inclusive of the end argument (i.e., x <= n <= y), use the random.randint(x, y) function.

In other words, random.randint(x, y) function is equivalent for random.randrange(x, y+1).

Download  Run Code

3. Using random.choice() function

The randint() or randrange() is the preferred way to generate a random number from a continuous sequence. To pick a random item from a sequence like a list or a tuple, you should use the random.choice() function.

Download  Run Code

4. Using secrets.randbelow() function

The random module is used to generate pseudorandom numbers. To generate a cryptographically secure random number, consider using the randbelow() function from the secrets module.

Download  Run Code

5. Using secrets.choice() function

The secrets.randbelow() function is preferred to cryptographically secure random numbers from a continuous sequence. To generate a cryptographically secure random number from a sequence like a list or a tuple, use the secrets.choice() function.

Download  Run Code

6. Using numpy.random.randint() function

With NumPy, you may use the numpy.random.randint(x, y) function.

That’s all about generating a random number in Python.