Python Random Module

Python Random module

The Python random module functions depend on a pseudo-random number generator function random(), which generates the float number between 0.0 and 1.0.

There are different types of functions used in a random module which is given below:

function of random module

  1. random.random()
  2. random.choice()
  3. random.randint()
  4. random.shuffle() 
  5. random.randrange() 
  6. random.seed()   

random.random()

This function generates a random float number between 0.0 and 1.0. 

random.randint()

This function returns a random integer between the specified integers.

but only one integer it does not matter how it is long

a = random.randint(0,10)

a can be 1,0,3,2,7,4,9

but not == 10

random.choice()

This function returns a randomly selected element from a non-empty sequence.

# importing "random"  module.

 import random 

# We are using the choice() function to generate a random number from 

# the given list of numbers. 

print ("The random number from list is : ",end="") 

print (random.choice([50, 41, 84, 40, 31]))

Output:

The random number from list is : 84

random.shuffle()

This function randomly reorders the elements in the list.

random.seed()

This function is used to apply on the particular random number with the seed argument. It returns the mapper value. Consider the following example.

  1. # importing "random" module.  
  2. import random  
  3. # using random() to generate a random number  
  4. # between 0 and 1  
  5. print("The random number between 0 and 1 is : ", end="")  
  6. print(random.random())  
  7.   
  8. # using seed() to seed a random number  
  9. random.seed(4)  

Output:

The random number between 0 and 1 is : 0.4405576668981033

random.randrange(beg,end,step)

This function is used to generate a number within the range specified in its argument. It accepts three arguments, beginning number, last number, and step, which is used to skip a number in the range. Consider the following example.


  1. # We are using randrange() function to generate in range from 100  
  2. # to 500. The last parameter 10 is step size to skip  
  3. # ten numbers when selecting.  
  4. import random  
  5. print ("A random number from range is : ",end="")  
  6. print (random.randrange(10050010))  

Output:

A random number from range is : 290

Comments