Python

Guide to Random Module in Python

Guide to Random Module in Python

Introduction

Often, our programs needn’t require user input all the time. Sometimes we desire a sense of randomness in our Python programs to give us various outputs. This is possible in Python with the help of the random module in Python. The random modules contain a large set of functions for various types of random outputs. One such prominent function is the rand() function in Python

The following sections will further elaborate on the different types of functions available

Functions in the Random Module

randint():

Syntax : randint(lower limit, upper limit)

The randint function of the random module generates a random integer lying between lower and upper limit with both endpoints included

Example

#Random integer between 0 and 10

n = random.randint(0,10)

print("Random number = ",n)

#Random integer between -21 and 0

n = random.randint(-21,0)

print("Random number = ",n)

write your code here: Coding Playground

Output

random()

Syntax : random()

The random function of the random module generates a random floating point number lying between 0 and 1

Example

#Random floating number between 0 and 1

n = random.random()

print("Random number = ",n)

n = random.random()

print("Random number = ",n)

write your code here: Coding Playground

Output

choice()

Syntax : choice(sequence)

The choice function of random module takes a sequence such as string,list or tuple and returns a random element from the passed sequence

Example

#Generating random character

str = "BoardInfinity"

print("Random character = ",random.choice(str))

#Generating random element from list

l = [23,45,67,89,90,111]

print("Random element from l = ",random.choice(l))

#Generating random from tuple

t = (23,45,67,89,90,111)print("Random element from t = ",random.choice(t))

write your code here: Coding Playground

Output

shuffle()

Syntax: shuffle(list)

The shuffle function of the random module in Python is used to jumble the different elements of a list. The shuffling overwrites the passed list and no list is returned.

Example

l = [12,15,17,23,11,98,100]

print("Before Shuffling :\n",l)

random.shuffle(l)

print("After Shuffling :\n",l)

Output

Activity: As an activity, using the functions in the random module develop a spinning wheel where every time an element is randomly deleted until a single element  remains which is the winning amount

Code

l = [100,250,400,550,700,800,1000,2000,3000,5000]

print("Spinning Wheel Prizes:")

for i in range(len(l)):

print(l[i],end = " ")

while(len(l)>1):

l.pop(l.index(random.choice(l)))

print("\nCongrats on winning $",l[0])

write your code here: Coding Playground

Output

Additional Random Methods in Python:

1. seed()

Random module in python does not actually generate a random number, but in reality, it rather generates pseudo-random numbers that are, these numbers are truly not random. The numbers can be predicted by determining the seed value which acts as the base for generating pseudo-random numbers

Syntax: random.seed(number)

Use cases

  1. This module could be used in the generation of pseudo-random encryption keys. These keys are associated with computers to prevent unauthorized access from any third-party source
  2. It enables the testing of applications that use a randomness factor by setting the initial seed value to obtain the required outputs

2. uniform()

This function of the random module is used to generate pseudo-random floating point numbers between the specified limits- upper and lower.

A good application of this function would be generating random numbers for lottery or casino games. The syntax of this function is given by

Syntax: random.uniform(lower limit, upper limit)

3. expovariate()

Python provides an inbuilt function such as expovariate() which is typically used to generate floating random numbers adhering to a distribution such as an exponential distribution for example. This finds use cases in places where we are dealing with the analysis of data involving packages such as NumPy, pandas, etc

Syntax: random.expovariate(lambda) where lambda is any non zero value

Similar to the function used to generate random numbers for the exponential distribution, some of the methods for generating random numbers for other distributions are listed below:

  1. gammavariate() - generate floating random numbers with gamma distribution
  2. gauss() - generate floating random numbers with a gaussian distribution
  3. longnormvariate() - generate random floating numbers with a log-normal distribution
  4. normalvariate() - generate random floating numbers with normal distribution
  5. paretovariate() - generate random floating numbers with Pareto distribution

4. sample()

Python allows the user to select a sample of the elements from a given sequence of elements through the sample() method. The syntax for selecting the sample of elements is given below:

Syntax: random.sample(sequence,k)

Where sequence can be a list, string, tuple, or set

And k is an integer specifying the length of the sample to be obtained

5. triangular()

Sometimes our test cases may require the generation of random numbers with a bias towards a particular value which can be achieved with the help of the triangular function. The syntax for this method is given by:

Syntax: random.triangular(low,high,mode)

Where low and high represent the lower and upper bounds of the random numbers to be generated and mode specifies the additional bias to be imposed while generating these numbers

Conclusion

The understanding and implementation of the different functions in the random module of Python were achieved through this exercise along with the implementation of a mini-game of a spinning wheel.