How to Generate a Random Number of Length N in Python

To generate a random number to a fixed length in Python for things like PINs, use the randint function from the random package and set the min and max values allowed like this:


random_number = random.randint(100, 999)


The example above will only produce numbers with a length of 3.


Python Random Number to Fixed Length Function

A more comprehensive solution would be to create a function that accepts any length value and returns a random number within that range. Here is an example of how to do that:


from random import randint

def random_to_fixed(n):
   range_start = 10**(n-1)
   range_end = (10**n)-1
   return randint(range_start, range_end)
print random_to_fixed(4)