Python Random Module
Random is an in-built module in python which is used to generate random numbers. The generated numbers are pseudo-random i.e, they are not fully random. This module is very useful when we want some random actions in our project. In this tutorial, we’ll cover everything about this module.
Installation
This module is already included in python so, we don’t have to install any third-party packages. We can import this module by using the following command.
import random
Some commonly used methods are:
random() method
This method is used to generate random float numbers between 0 to 1. This method takes no arguments.
Input
import random
a = random.random()
print(a)
Output
0.8615024546047799
radiant() method
This method is used to generate random integer numbers between a given range.
Input
import random
a = random.randint(5,200)
print(a)
Output
192
choice() method
This method is used to choose a random element from a sequence
Input
import random
a = "Hello World"
print(random.choice(a))
Output
d
shuffle() method
This method is used to shuffle a sequence in random order
Input
import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print(a)
Output
[8, 4, 3, 2, 6, 9, 1, 5, 7]
uniform() method
This method is used to generate a random float value between two given parameters
Input
import random
print(random.uniform(2,5))
Output
2.9185331441263527
randrange() method
This method is used to generate a random number between given inputs
Input
import random
print(random.randrange(1,5))
Output
0.8615024546047799
Some more methods are -
Methods |
Usage |
getrandbits() |
this method is used to generate random bits |
seed() |
seed is a positive integer which is used to initialize a random number generator |
sample() |
this method is used to convert a sequence to a specific size randomly |
gauss() |
this method is used to generate a random gaussian distribution |
choices() |
this method is similar to choice() method but it stores a value in a list |