Learn Python – Python random randrange()- Basic and advance

The Python random module approves generating random numbers. The generated numbers are a sequence of pseudo-random numbers, which are primarily based on the used function. There are distinctive sorts of functions used in a random module to generate random numbers, such as random.random(), random.randint(), random.choice(), random.randrange(start, stop, width), and many more.

Here, we will discuss the randrange() feature of the random module. The randrange() feature is used to generate a random quantity between the targeted range in its parameter. It accepts three parameters: starting number, stop number, and width, which is used to bypass a number in the range.

Syntax of random.randrange()

random.randrange(start, stop[, width])  

The random.randrange() feature returns a random integer range within the given range, i.e., begin and stop. The random.randrange() feature takes three parameters as an enter start, stop, and width. Out of these three parameters, the two parameters begin and width are optional.

The start parameter is a starting or lower limit integer number in a random range. If the start parameter is not passed in parameter, it takes default value 0 (zero).

A stop parameter is the last number or upper limit integer number in a random range.

The width parameter is a range between each number in the random sequence. This parameter is optional, and if the width parameter is not passed in parameter, it takes default value 1 (one).

The randrange(start, stop, width) feature does not include the end parameter whilst producing the random integer number. The end parameter is exclusive, and it now not receives generated in a random number.

Look at this random.randrange(3, 30, 3) characteristic that will generate any random integer value between 3 to 30 like 3, 6, 9, 12, …27. But this characteristic by no means consists of 30 whilst producing a random number.

Generating a random in an application constantly been important, and it has numerous real-time makes use of in every day life. For example, producing and sending a random wide variety to a client as an OTP (one-time-password) for making a secure transaction. Another instance of producing a random number is used whilst enjoying the ludo game to generate a random cube number.

Examples 1: random.randrange() generate a random integers wide variety within the given vary

Let’s see an instance where we are generating a random integer quantity inside a given range. This example shows all the specific forms of random.randrange() function.

import random  
print("Generating random number within a given range ")  
# Random number between 0 and 29  
number1 = random.randrange(30)  
print("Random integer: ", number1)  
# Random number between 10 and 29  
number2 = random.randrange(10, 30)  
print("Random integer: ", number2)  
# Random number between 25 and 200 divisible by 5  
number3 = random.randrange(25, 201, 5)  
print("Random integer: ", number3)  

Output:

Example 2: Generate a random integer variety range (multiple) of n

Let’s generate the random integer variety between 5 to 100, which is a vary of 5 such as 5, 10, 25, …, 90, ninety five

import random  
#print "Random number range (multiple) of 5"  
number = random.randrange(5, 100, 5)  
print("Random number range (multiple) of 5 is ", number)  

Output:

Example 3: Generate the random integer range of a unique length

You can also generate a random integer wide variety of a particular length. If you desire to generate a random variety of size 3, enter the start and quit parameter in randrange() function as least wide variety of 3 digit length (100) and least number of four digit size (1000) because it generates a random quantity of three digit structure a hundred to 999 the place 4 digits (1000) is excluded.

Example: Generate a random number of three digit using random.randrange()

import random  
number1 = random.randrange(100, 1000)  
print("First random number of length 3 is: ", number1)  
number2 = random.randrange(100, 1000)  
print("Second random number of length 3 is: ", number2)  

Output:

First random number of length 3 is: 813
Second random number of length 3 is: 770

Example 4: Generate a random negative integer number:

Let’s see an example that generates a random bad integer wide variety between -50 to -10.

import random  
randomNagativeInteger = random.randrange(-50, -10)  
print("Random negative integer number between -50 to -10")  
print("Random negative integer number between -50 to -10 is: ",randomNagativeInteger)  

Output:

Random negative integer number between -50 to -10
Random negative integer number between -50 to -10 is:  -43

Example 5: Generate random positive or bad integer range

import random  
number1 = random.randrange(-5, 5)  
print(number1)  
number2 = random.randrange(-5, 5)  
print(number2)  

Output:

-5
0

Note that the parameter begin and stop, which is surpassed in random.randrange() feature must be in increasing order, such as random.randrange(5, 10) or random.randrange(-20, -10). The start parameter usually be smaller than the cease parameter; otherwise, this function generates an error as “Traceback (most latest name last) and increase ValueError empty range for randrange()”.

For example:

Look at this example in which we are violating the rule via passing the start parameter larger than the stop parameter in random.randrange() function, which generates an error message as:

import random  
randomNumber = random.randrange(10,5)  

Output:

Some of the other functions of Python’s random module that are used to generate numbers randomly are:

choice()

randint()

sample()

sort()

random.choice()

Python random module has a choice() function used to choose a random element from a listing or other sequence. A random.choice() characteristic is used to returns a random thing from the list of values.

Syntax of ramdom.choice()

random.choice(sequence)  

or

random.choices(sequence, k=l)  

Here the parameter sequence can be string, list, tuple, and random.choice() only a single random element.

In the random.choices() function k is the range of factors to be returned. Suppose we do not mention the price for k parameter the random.choices() returns a single item from the sequence or list.

Example 1:

In this example, we are imparting on sequence (list) as a parameter and returning a single random element.

import random  
listValue = [5,10,15,20,25,30]  
item = random.choice(listValue)  
print("random item from list is: ", item)  

Output:

random item from list is:  10 

Example 2:

The random.choices() characteristic is typically used for returning random factors with a number possibilities. This characteristic additionally takes weight (k) the range of random choices. For example, we favor to print three random movies identify from list of 5 movies.

import random  
movieList = ['Matrix', 'Terminator', 'Black Panther', 'Avengers', 'Titanic']  
randomMovies = random.choices(movieList, k=3)  
print("random movies from list are: ", randomMovies)  

Output:

random movies from list are:  ['Avengers', 'Black Panther', 'Titanic']

random.randint()

Python random.randint() characteristic is used to generate a random integer wide variety inside the specified range.

Syntax:

random.randint(start, stop)  

The random.randint() feature takes two parameters start, which is a beginning range, and stop, which is an end range. Both parameters (start, stop) are blanketed while generating a random number.

Example of random.randint() producing a list of random integer

This example will create a listing of a couple of random integers the usage of the randint() function. Generating a listing of 5 random integers between 1 and 100, each values are inclusive.

import random  
randomListValue = []  
# specifing length of list equal to 5  
for i in range(0, 5):  
    # generates random numbers from 1 to 100  
    randomListValue.append(random.randint(1, 100))  
print("Printing list of 5 generated random numbers")  
print(randomListValue)  

Output:

Printing list of 5 generated random numbers
[65, 82, 3, 39, 40]

However, there may also be a possibility that the random.randint() function returns a duplicate variety in the output result. To avoid the duplicate random integer quantity in a result, use random.sample() function.

random.sample()

In the above example, there may also be a opportunity that random.randint() generates the replica random number from the list. If you favor to generate special random numbers from a list, use random.sample() function.

The random.sample() function generates unique factors from a set, list, and different sequences. Python’s random.sample() function lets in random sampling of extra than one aspect within a vary from the listing except duplicating.

Example of a random.sample() to generate random factors from a listing besides duplicates:

In this example, we will generate 10 random integers from the range zero to one hundred

import random  
# Generate 10 unique random numbers within a range  
randomList = random.sample(range(0, 100), 10)  
print(randomList)  

Output:

[15, 17, 16, 66, 34, 85, 71, 82, 97, 48]

If you prefer to generate a list of random numbers and each of them ought to be more than one of ‘n’, then use the step parameter of range() function.

For example, producing 10 random integers which are a couple of of 5 from the vary 0 to 100 the usage of random.sample(range(0, 100, 5), 10).

import random  
# Generate 10 unique random numbers within a range  
randomList = random.sample(range(0, 100, 5), 10)  
print(randomList)  

Output:

[75, 40, 20, 55, 15, 10, 5, 90, 95, 70]

List sort()

The Python sort() feature is used to kind the random integer numbers of the listing in ascending order (by default). We can additionally sort the list value in descending order with the aid of specifying its order reverse = True. The default value of reverse is False.

Example 1: sort() sorting list factors in ascending order

In this example, we will generate a random listing of 5 numbers in a vary of 50 to one hundred with the width of 5 and type them the usage of sort() function.

import random  
randomList = random.sample(range(50, 100, 5), 5)  
print("Before sorting random integers list")  
print(randomList)  
# sort the list ascending order by default  
randomList.sort()  
print("After sorting random integers list")  
print(randomList)  

Output:

Before sorting random integers list
[90, 80, 60, 55, 85]
After sorting random integers list
[55, 60, 80, 85, 90]

Example 2: sort() sorting listing elements in descending order

In this example, we will type the list factors in descending order using randomList.sort(reverse=True).

import random  
randomList = random.sample(range(50, 100, 5), 5)  
print("Before sorting random integers list")  
print(randomList)  
# sort the list descending order  
randomList.sort(reverse=True)  
print("After sorting random integers list")  
print(randomList)  

Output:

Before sorting random integers list
[70, 50, 80, 90, 85]
After sorting random integers list
[90, 85, 80, 70, 50]