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.
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.
Example 1: Generate Random Number of Length
In the following example, we will define a function that generates and returns a random number of length passed as argument.
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))
When you run this python script, you will get a similar output, but may be with different random numbers.
94839 1176870 4216 63706007
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.
- Python Program to Generate Random Float
- PyTorch Create Tensor with Random Values and Specific Shape
- Python Random Module Examples
- Python – Generate Random String of Specific Length
- Python Numpy – Create Array with Random Values
- Python Program to Flip a Coin
- Python Program to Generate Random Password
- Python – Generate a Random Number – Positive or Negative