Python Random Module

 

Python Random Module

Python contains many files that can be imported into a python code and used whenever we want. One of those modules is the random module. It is a good practice to know about the modules in python.

This module is used to generate random numbers in python. Whenever we write a code and want to generate a random number in our code, then we use the random module in python.

Using the Python random module

The random module is an in-built module in python. It generates pseudo-random numbers that are not exactly random but seem that way.  This can be used in many ways as generating random values, printing random values, selecting a random index in an array, etc.

Before using this module, we have to import it first. We can import the random module using the import statement.

import random

As we already know from the above paragraph, that random module gives pseudo-random numbers, which means that the number is not random. They depend on the seeding value. Same seeding value will result in the same numbers. If any number has the same seeding value, then the random number will be the same.

Example

import random

 

# printing a random value from the list

l = [10, 20, 30, 40, 50, 60]

print(random.choice(l))

Output

20

Explanation

In this code, we have generated a random number using the following python random module.

Creating Random Integers

In python, the random.randint() method is used for generating random integers between the given range.

Syntax :

randint(start, end)

Example

import random

 

rndm_num1 = random.randint(10, 50)

print("Random number between 10 and 50 is % s" % (rndm_num1))

 

# Generating a random number between two negative integer range

rndm_num2 = random.randint(-60, -20)

print("Random number between -60 and -20 is % d" % (rndm_num2))

Output

Random number between 10 and 50 is 36

Random number between -60 and -20 is -35

Explanation

In the above code, we have imported the random module. After that, we used the random.randint() method to generate a random number between the given range.

Creating Random Floats

In python, the random.random() method is used to generate random floats between the range of 0 to 1.

Syntax: 

random.random()

Example

from random import random

      

# Prints random item

print(random())

 

Output

 

0.10381936922577129

 

Explanation

In the above code, we have used the random module to import the random value between the range of 0 to 1. First, we imported the module using the import statement. After that, we used the random module to print the value.

 

Selecting Random Elements

 

Example

import random

 

l = [10, 20, 30, 40, 50, 60]

print(random.choice(l))

 

# printing a random item from the string

str = "tutorialsandexamples"

print(random.choice(str))

 

# printing a random item from the tuple

tpl = (1, 2, 3, 4, 5)

print(random.choice(tpl))

 

Output

30

a

5

 

Explanation

In the above code, we have used the random.choice() method is used to find the random number in a given list, string, and tuple. We have used three variables. One for the list (l). Another one is for string (str). Last one is for tuple (tpl).

 

Shuffling List

 

Syntax

random.shuffle(sequence, function)

 

Examples

import random

 

# declaring a list

lst = [10, 20, 30, 40, 50]

print("The original list : ")

print(lst)

 

# first shuffle of the list

random.shuffle(lst)

print("\nAfter the first shuffle, the list : ")

print(lst)

 

# second shuffle

random.shuffle(lst)

print("\nAfter the second shuffle, the list : ")

print(lst)

 

Output

The original list :

[10, 20, 30, 40, 50]

 

After the first shuffle, the list :

[10, 50, 30, 20, 40]

 

After the second shuffle, the list :

[40, 20, 50, 10, 30]

 

Explanation

In the above code, we used random.shuffle() module to shuffle the given list. In this code, we have shuffled it two times. After shuffling the first time, we printed the value of the list. Similarly, after shuffling the second time, we printed the list.

 

List of all the functions in Random Module

·        Seed()

·        getstate()

·        setstate()

·        getrandbits()

·        randrange()

·        randint()

·        choice()

·        choices()

·        sample()

·        random()

·        uniform()

·        triangular()

random.seed( ) module

In python, the random() function is mostly used for generating random numbers. These numbers are not actually random. Instead, this is used to generate pseudo-random numbers. That determines that these randomly generated numbers can be determined beforehand. The random() function generates numbers for some values. These values are called seed values.

 

 

Example

import random 

for i in range(10): 

    # We can use any number in place of '0'.

    random.seed(0)  

   # Generating a random number between 1 to 1000.

    print(random.randint(1, 1000)) 

 

Output

865
865
865
865
865

 

Explanation

In the above line of codes, we have used the random.seed() module to get the seed value of a particular number. Then we used another module random.randint() to print the random number in the range.

Example 2:

# importing the random module

import random

 

random.seed(6)

 

# random numbers between 1 and 1000.

print(random.randint(1, 1000))

 

# for getting the same random number again,

random.seed(6)

print(random.randint(1, 1000))

 

# If we don’t use the seed function then the result will be unpredictable.

print(random.randint(1, 1000))

 

Output:

244

244

607

Explanation

In the above line of code, we have used the random.seed() module to store the seeding value, whereas we have used the random.randint() module to print the random number between a given range.

Uses of random.seed()

·       In python, the random.seed() module is used in the generation of a pseudo-random encryption key. An Encryption key is an important part of computer security. Using this module makes the optimization of codes easy.

 

random.getstate() 

In the random module, the getstate() method of the random module returns an object with the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. There are no parameters passed in this method.
Example 1:

import random

 

# variable is used for remembering the state

s = random.getstate()

# printing 10 random numbers in the range of 1-30

print(random.sample(range(30), k = 10))

# restore state using setstate method

random.setstate(s)

# print the first five same random numbers as above

print(random.sample(range(30), k = 5))

Output

[1, 18, 15, 8, 13, 14, 7, 19, 9, 10]

[1, 18, 15, 8, 13]

Explanation

In the above code, we have used the random.getstate() method to save the method. After that, we printed a list of random numbers in a given range. Then using the setstate() method, we used the random saved state to print the same random value again.

Example2

import random

 

x = [1, 2, 3, 4, 5, 6]    

# Getting state using the variable

s = random.getstate()

print(random.choice(x)) 

# using the saved state

random.setstate(s)

#prints the same random value

print(random.choice(x))

 

Output

2

2

Explanation

In the above code, we have used the random.getstate() module to save the state of the list. After that, we used the random.choice() module to get the random value from the given list x. Then we will use the setstate() method to get the saved state. This method is used to print the same random value.

random.setstate()

The setstate() method requires a state object as a parameter which can be obtained by invoking the getstate() method.

Example

# importing the random module

import random

 

# capturing the current state using the getstate() method

s = random.getstate()

 

# printing a random number of the captured state

x = random.random()

print("Random number is: "+ str(x))

 

# printing another random number

x = random.random()

print("Another random number is: "+ str(x))

 

# restoring the captured state using the setstate() method

random.setstate(s)

 

# now printing the same random number as in the captured state

x = random.random()

print("The random number of the previous state is: "+ str(x))

 

Output

Random number is: 0.38741366638521711

Another random number is: 0.5677256188116784

The random number of the previously state: 0.38741366638521711

Example2

# import the random module

import random

  

  

l = [1, 2, 3, 4, 5]  

  

s = random.getstate()

  

 

print(random.sample(l, 4)) 

  

# restoring the captured state using the setstate() method

random.setstate(s)

  

# now printing the same list of random items

print(random.sample(l, 4)) 

 

Output

[1, 4, 3, 5]

[1, 4, 3, 5]

Explanation

In the above code, we used the setstate() method to get the same random module again. In this code, we have used the setstae() and getstate() method.

 

random.getrandbits() 

In python, the getrandbits() method of the random module is used for returning an integer to the specified number of bits. The number of bits that are needed in the result is passed as a parameter in the method.

 

Example 1: 

# importing the random module

import random

 

# getting a random number with 3 bits

print(random.getrandbits(3))

 

# getting random number with 16 bits

print(random.getrandbits(16))

 

Output

5

43142

Explanation

In the above code, we have used the getrandbits() method to print a value of 4 bits and 16 bits.

Example2

# importing the random module

import random

 

# This prints 5 random numbers with 4 bits

for i in range(4):

    print(random.getrandbits(4))

Output

12

3

13

11

Explanation

In the above code, we have used the for loop to print 5 random numbers of 4 bits using the getrandbits() method.

 

randrange()

Python offers a function that can generate random numbers from a specified range and allows room for steps to be included, called randrange(), in the random module.

Example

import random

 

print ("Random number: ",end="")

print (random.randrange(200))

 

print ("Random number: ",end="")

print (random.randrange(5,100))

 

print ("Random number from 5-100 skip 5 is : ",end="")

print (random.randrange(5,100,5))

Output

Random number: 26

Random number: 58

Random number from 5-100 skip 5 is: 90

Comments

Popular posts from this blog

What is Modular Programming? Where is it used?

What is Hibernate Framework?

Ellipse command in AutoCAD