Generating a Random Number of Specific Length in Python

Python has a built-in module random for generating random numbers.

The random module provides the following functions for generating random numbers in python:

  • random.randint()
  • random.randrange()
  • random.sample()

random.randint() Function

The randint(start, end) function accepts two arguments and returns an integer value between the function's starting and ending points.

The following example prints a 4 digit random number between 1000 to 9999:


import random

print(random.randint(1000,9999))
  

The output of the above example will look like this:

7283

random.randrange() Function

The randrange(start, stop, [width]) function returns an integer value between the function's starting and ending points. The randrange() function accepts three parameters: start, stop, and width, out of which the two parameters start and width are optional. If the width parameter is not specified, the default value, 1 is used.

The following example prints a 6 digit random number between 100000 to 999999:


import random

gen_ran_num = random.randrange(100000,999999)
print(gen_ran_num)

The output of the above example will look like this:

345345

random.sample() Function

The sample() function returns a list of items that has the length of our choice.

The following example prints a list of 5 numbers with values between 1 to 100:


import random

gen_ran_num = random.sample(range(1,100),5)
print(gen_ran_num)

The output of the above example will look like this:

[65, 28, 27, 40, 71]