Python Program to Generate a Random Number of Specific Length

Python – Generate a Random Number of Specific Length

We know that randint() generates a random number. In this tutorial, we going to simulate a specific scenario where the random number should be of specified lenght.

Using randint() function of python random module, you can generate a random number of specified length, using its minimum and maximum parameters.

Following is the snippet that demonstrates the usage of randint() function.

import random
randomnumber = random.randint(minimum, maximum)

To generate a random number of given length, all we have to do is set the minimum and maximum values.

Consider that the length of the random number that we should generate is N. Then minimum would be pow(10, N-1) and maximum would be pow(10, N)-1.

Examples

1. Generate random number of specific length

In the following example, we will define a function that generates and returns a random number of a specific length, passed as argument to it.

Python Program

import random

def randN(N):
	min = pow(10, N-1)
	max = pow(10, N) - 1
	return random.randint(min, max)

print(randN(5))
print(randN(7))
print(randN(4))
print(randN(8))
Run Code Copy

When you run this python script, you will get a similar output, but may be with different random numbers.

Output

94839
1176870
4216
63706007

Summary

In this tutorial of Python Examples, we learned how to generate a random number of specific length using randint() method with the help of well detailed examples.

Code copied to clipboard successfully 👍