Search code examples
pythonrandom

How to generate a random number with a specific amount of digits?


Let's say I need a 3-digit number, so it would be something like:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56

Solution

  • You can use either of random.randint or random.randrange. So to get a random 3-digit number:

    from random import randint, randrange
    
    randint(100, 999)     # randint is inclusive at both ends
    randrange(100, 1000)  # randrange is exclusive at the stop
    

    * Assuming you really meant three digits, rather than "up to three digits".


    To use an arbitrary number of digits:

    from random import randint
    
    def random_with_N_digits(n):
        range_start = 10**(n-1)
        range_end = (10**n)-1
        return randint(range_start, range_end)
        
    print random_with_N_digits(2)
    print random_with_N_digits(3)
    print random_with_N_digits(4)
    

    Output:

    33
    124
    5127