Exploring random Module in Python

In this module, we will learn about the random module in python. The random module provides access to functions that support many operations.
random module is used to generate the random numbers from the various distributions.
For integer, This module selects the uniform numbers from a specified range. for sequences, there is a uniform selection of a random element from the sequence.

You can build these games using this random module

Random Module in Python

The Random module in Python is imported as

import random

The Random Module contains the following useful Functions:

choice() function in random module

  • choice()

this function is used when we want one item from a sequence or range.every time when program executes it generates the random number different from previous.

For example:

import random 
number=[1,2,3,4,5,6,7,8,9]
print(random.choice(number))

output:

6

randrange() function in random module

  • randrange(start,stop,step)

This function is used when we want a number from the specified range. randrange function takes three arguments start, stop and step. By default start and step takes 0 and 1 respectively.




import random 
print(random.randrange(10,40,2))

Output

16

seed() function in random module

  • seed()

The seed() function can be used to seed the pseudo-random number generator, taking an integer as seed value. This function maps a particular random number with seed argument mentioned.

import random 
print(random.seed(7))

Output:

0.3238327648331623

uniform() function in random module

  • uniform(m,n)

This function returns a floating point random number between its argument(m,n).

import random 
print(random.uniform(4,8))

Output:

5.1541154168

random() function in random module

  • random()

This function used when we want a floating point number between 0 and 1.

import random
print(random.random())

Output:

0.598632145

radnint() function in random module

  • randint(m,n)

This function is used when we want a random integer between its argument m and n.

import random 
print(random.randint(1,9))

Output:

5

triangular() function in random module

  • triangular(low, high, mode)

This function returns the floating point number N such that low<=N<=high. By default low=0, high=1 and The mode argument defaults to the midpoint between the low and high.

import random 
print(random.triangular(5,200))

Output:

113.8685896288554652

You may also read:


Leave a Reply

Your email address will not be published. Required fields are marked *