Python random randrange() and randint() to generate random integer number within a range

Posted in /  

Python random randrange() and randint() to generate random integer number within a range
vinaykhatri

Vinay Khatri
Last updated on March 1, 2024

    In Python's random module, we have two functions randrange() and randint(), that can generate random integer numbers. In this Python tutorial, we will discuss these two functions in detail and learn how to use them. Both of these functions can generate random integer numbers based on the given range. And by the end of this tutorial, you will have an understanding of the syntax and usage of these two functions.

    So let's get started.

    How to use the random.randint() function in Python?

    The randint() function stands for random integer, and it returns a random integer number between the specified range.

    Syntax of randint() function in Python

    import random 
    
    random.randint(start, stop)

    randint() is a method of random module, to use it, we need to import the random module in our script. We could also import the randint() method only using the statement from random inport randint .

    Arguments

    The randint(start, stop) method accepts two arguments, and both are mandatory.

    • start : It must be an integer value, defining the starting range for the random number.
    • stop : It is also an integer value, defining the endpoint for the random number.

    Return value of randint() function

    The randint() function returns a random integer value N between a start and stop ( start <= N <= stop ).

    Examples

    Let's see some examples of random.randint() function that generates random integers.

    Example 1

    Let's create a 5-digit OTP number using randint() function. The lowest and highest 5-digit numbers are 10000 and 99999. And these two will be the start and stop values for the randint() arguments.

    #load the random module
    import random
    
    start = 10000
    stop = 99999
    
    #generate a 5 digit otp
    otp = random.randint(start, stop)
    
    print("Your 5 digit otp is: ", otp)

    Output

    Your 5 digit otp is: 85927

    Example 2

    Let's write a script that generates a number between 1 to 6 for a dice roll.

    #load the random module
    import random
    
    start = 1
    stop = 6
    
    #random dice roll
    dice_roll = random.randint(start, stop)
    
    print("You got: ", dice_roll)

    Output

    You got: 3
    
    Note: The randint() function only accept the integer values, if we pass a float or string values we will recive the ValueError. The value of start argument must be less than stop otherwise it will raise the TypeError and ValueError .

    How to use the random.randrange() function in Python?

    With the random.randrange() function, we can generate a random number between a specified range.

    Syntax of randrange() function

    The randrange() function has two syntax

    Syntax 1

    import random
    
    random.randrange(stop)

    Return value

    With single argument stop, the randrange() function returns a random Integer number N between 0 to stop ( 0<=N <stop ).

    Example

    #load the random module
    import random
    
    #generate a random number between 0 and 100
    print(random.randrange(100))

    Output

    86

    The randrange() function does not include the stop number, it will always generate a random number between 0 and stop-1.

    Syntax 2

    random.randrange(start, stop, step)

    Return value

    It returns an integer number N between start and stop-1 having a step number of gaps between every Number.

    Parameters

    The randrange(start, stop [,step]) function can accept 3 argument values start, stop and step.

    1. start : It must be an integer value defining the starting range to select the random number.

    2. stop : It also needs to be an integer value representing the upper limit of the generated random number.

    3. step : It is an optional argument value whose default value is 1. It defines the step gap between the numbers start and stop .

    For example, the random.randrange(2, 10, 2) will always pick a random number from these number [2, 4, 6, 8] , 2 is the start argument value, so it will be included but not 10.

    Example

    Let's create a program that randomly generates an even random number between 10, and 100 (10 and 100 both must also be included)

    #load the random module
    import random
    
    #generate an even random number between 10 and 100
    print(random.randrange(10, 101, 2))

    Output

    48

    Generate a random number of specific length

    With the randrange() function, we can generate a random number of fixed lengths. To do this, all we need to do is pass the start argument's the lowest number of that length and stop the highest+1 number.

    Example

    let's write a Python script that generates 5 random numbers of 4 digits.

    #load the random module
    import random
    
    for i in range(5):
        #generate a random 4 digit number
        print(random.randrange(1000, 10000))

    Output

    5250
    4895
    2930
    6537
    7504

    The randrange() function can generate a single random number at a time. To generate multiple random numbers with randrange() we have to call it multiple times using a loop.

    How to generate a Random negative integer in Python?

    We can either use randint() or randrange() functions to generate a random negative integer number.

    Example 1

    Let's first create a negative integer number with randint()

    #load the random module
    import random
    
    #generate a random negative integer number between -100 to -1
    print(random.randint(-100, -1))

    Output

    -69
    

    Example 2

    Now generates a negative random number with randrange()

    #load the random module
    import random
    
    #generate a random negative integer number between -100 to -1
    print(random.randrange(-100, -1))

    Output

    -74

    You can see that both the examples have the same syntax and return a random number between -100  and -1. But the difference is randint() will include -1 in its random numbers but randrange() won't.

    How to generate a positive and negative integer number in Python?

    Suppose we want to generate a random number between -100 to 100. How will we do that? The answer is simple if we want to include both ends, we will use the randint() function, or if we want to exclude the stop end, we will use the randrange() function.

    Example

    #load the random module
    import random
    
    #generate a random integer number between -100 to 100
    print(random.randint(-100, 100))

    Output

    -46

    How to generate a list of random integer numbers?

    To generate a list of random integer numbers, we have to call the randint() or randrange() function multiple times and append every call result to the list. Let's see it through an example

    Example

    Suppose we need to write a Python script that generates a list of 10 random integers ranging from 100 to 1000.

    #load the random module
    import random
    
    #initialize an empty list
    random_list = []
    
    for i in range(10):
        #generate a random integer number between 100 to 1000
        random_num = random.randrange(100, 1000)
    
        #add the random number to the list
        random_list.append(random_num)
    
    print("The List of Random Numbers: ", random_list)
    

    Output

    The List of Random Numbers: [842, 165, 959, 793, 307, 191, 207, 475, 275, 124]
    

    How to create a list of random numbers without duplicates?

    In the above example, we learned how we could create a list of random numbers, but there is a high chance that you may get duplicate integer numbers while creating a random number list. To create a list of random integers without any repetitive number, we can use the random module sample() function. The sample(sequence, k) function returns a list of k randomly selected unique items from the sequence.

    Example

    #load the random module
    import random
    
    #list of random numbers without duplicates
    random_list = random.sample(range(100, 1001), k=10)
    
    
    print("The List of Random Numbers: ", random_list)

    Output

    The List of Random Numbers: [108, 439, 408, 407, 579, 668, 504, 572, 196, 228]
    Note: In the sample(sequence, k) function the value of k must be less than the length of the sequence.

    How to sort a list of random numbers?

    Once we have a list of the random numbers, we can perform the sort() method on that list and sort in ascending or descending order.

    Example

    #load the random module
    import random
    
    #list of random numbers without duplicates
    random_list = random.sample(range(100, 1001), k=10)
    
    #sort the list
    random_list.sort()
    
    print("The sorted List of Random Numbers: ", random_list)

    Output

    The sorted List of Random Numbers: [183, 320, 518, 623, 669, 721, 748, 757, 861, 962]

    How to create a secret and secure random number in Python ?

    Python has an inbuilt secrets module, that can generate cryptographically strong random numbers. We can use this module to create secure random numbers in Python.

    Example

    import secrets
    
    # generate a secure random number between 0 to 100 [0, 100) 
    random_num = secrets.randbelow(100)
    
    print(random_num)

    Output

    97

    Note: The secrets module is only available for Python 3.6 and above version.

    How to create a Multidimensional array of integers in Python?

    Python has a third-party package called numpy that is popular for its powerful array and its methods. We can use this library's random method to generate a multidimensional array.

    syntax

    import numpy 
    numpy.random.randint(start, stop, size=(rows, columns))

    Note: Numpy is a third-party Python package. Before using it, we have to install it for our Python environment. To install, we can run the pip install numpy command on our command prompt or terminal.

    Example

    let's create a matrix of 6X6 with random integers ranging from 100 to 200

    import numpy as np
    
    #generate a matrix of size 6X6 with random integers 
    arr = np.random.randint(100, 200, size = (6, 6))
    
    print(arr)

    Output

    [[100 102 182 191 132 106]
    [102 131 159 130 150 139]
    [112 116 199 179 113 157]
    [191 170 155 117 109 132]
    [193 147 148 153 140 135]
    [173 170 138 157 141 188]]

    Example 2

    We can also call the randint() method multiple times to create a matrix.

    import random
    
    #initialize an empty array
    matrix = []
    
    #random integer start and end points
    start, stop = 100, 200
    
    #matix size 6X6
    rows, columns = (6,6)
    
    for i in range(rows):
        #an empty list for row data 
        row = []
        
        for j in range(columns):
            #create a random integer
            #add it to the row
            row.append(random.randint(start , stop))
            
        #add the a_row data to the matrix
        matrix.append(row)
    
    print(matrix)
    

    Output

    [[124, 161, 190, 186, 179, 140], 
     [200, 176, 131, 140, 175, 126],
     [176, 167, 141, 114, 169, 166],
     [169, 161, 182, 132, 102, 165],
     [118, 140, 186, 160, 129, 126],
     [196, 171, 185, 136, 110, 185]
    ]

    Conclusion

    In this tutorial, we learned how we could generate random integer numbers in Python. The random module has two methods randint() and randrange() that can be used to create random integer numbers between a specified range. The randint(start, stop) function accepts two arguments, start & stop, and returns a random integer number. And the randrange(start, stop, step) function can accept 3 arguments and also return a random integer number between the start and stop.

    Python Interview Questions on the random module

    1. Write a Program to print a 3-digit random number.

    import random
    
    #3 digit random number
    num = random.randint(100, 999)
    
    print(num)

    OR

    import random
    
    #3 digit random number
    num = random.randrange(100, 1000)
    
    print(num)
    

    2. What is the difference between randint and randrange() functions?

    The randint(start, stop) function will return a random integer number N between start and stop , and it includes start and stop both in the random values. randrange(start, stop, step) , can accept three arguments and it also return a random integer number between start and stop , but it include start and exclude the stop value.

    3. What exception will be raised if we pass a string value to the randint(), or randrange() function?

    Ans: randint() and randrange() functions only accept integer values if we pass a string or any other data type to them; Python will raise the TypeError exception.

    4. What will happen if the value of the start argument is larger than the stop?

    Ans: In case of randint(start, stop) function, if the value of start is larger than stop, we will receive the ValueError. In randrange(start, stop, step) , if the value of start is larger than stop , we have to specify the step value in negative otherwise, we will receive the ValueError.

    People are also reading:

    Leave a Comment on this Post

    0 Comments