Random number generation is the process of generating a number that cannot be predicted better than by a random chance. Random numbers are used in cryptography, electronic noise simulation and gambling etc.

Most computer generate pseudo random numbers which are not true random numbers. They use algorithms to generate random numbers.

Python uses Mersenne Twister algorithm for random number generation. In python pseudo random numbers can be generated by using random module.

If you would like to become a Python certified professional, then visit Mindmajix - A Global online training platform:  Python Certification Training”  Course.  This course will help you to achieve excellence in this domain.

Python Random Number Generator:

Example

from random import *

print random()

output: It will generate a pseudo random floating point number between 0 and 1.

from random import *

print randint(10, 100)

output: It will generate a pseudo random integer in between 10 and 100

from random import *

print uniform(1, 10)

output: It will generate a pseudo random floating point number between 1 and 10.

import random

list = ['1','4','7','Hi']

print random.choice(list)

output: It will output any of the four objects in the list randomly.

import random

list = [1,2,3,"4", "l90", "hi"]

random.shuffle(list)

print (list)

output: It will shuffle the list and randomly and print the shuffled list.

import random

for i in xrange(5):

print random.randrange(0, 100, 2)

Subscribe to our youtube channel to get new updates..!

output: It will output 5 random numbers from range 0 to 100. 2 is the step need to be added into randomness.

The syntax is:

random.randrange( start, stop, step )
import random

str = "helloworld"

list = ['a','b','c','d','e','f','o','l']

print random.sample(str, 4)

print random.sample(list, 4)

output: It will output a list of 4 random characters from string and list.

The syntax is:

random.sample (sequence, length)

Sample output:

['o', 'h', 'l', 'w']

['f', 'b', 'c', 'a']

Frequently Asked Python Interview Questions & Answers

Generate Random Number Using Seed

A seed is a number that is used to initialize a pseudo random number generator. Seed guarantees that if you start from same seed you will get the same sequence of random numbers.

import random

random.seed(5)

print(random.random())

print(random.random())

print(random.random())

output:

0.62290169489

0.741786989261

0.795193565566

Related Page: Introduction To Python Programming

List of Functions in Python Random Module:

seed(a=None, version=2) Initialize the random number generator
getstate() Returns an object capturing the current internal state of the generator
setstate(state) Restores the internal state of the generator
getrandbits(k) Returns a Python integer with k random bits
randrange(start, stop[, step]) Returns a random integer from the range
randint(a, b) Returns a random integer between a and b inclusive
choice(seq) Return a random element from the non-empty sequence
shuffle(seq) Shuffle the sequence
sample(population, k) Return a k length list of unique elements chosen from the population sequence
random() Return the next random floating point number in the range [0.0, 1.0)
uniform(a, b) Return a random floating point number between a and b inclusive
triangular(low, high, mode) Return a random floating point number between low and high, with the specified mode between those bounds
betavariate(alpha, beta) Beta distribution
expovariate(lambd) Exponential distribution
gammavariate(alpha, beta) Gamma distribution
gauss(mu, sigma) Gaussian distribution
lognormvariate(mu, sigma) Log normal distribution
normalvariate(mu, sigma) Normal distribution
vonmisesvariate(mu, kappa) Vonmises distribution
paretovariate(alpha) Pareto distribution
weibullvariate(alpha, beta) Weibull distribution

Python Secret:

Python 3.x.x added a new secret module for generating secure random. It has three functions. Let’s see the example below.

Example

import secrets

import string

letters = string.ascii_letters + string.digits

password = ''.join(secrets.choice(letters) for i in range(10))

print(password)

output: it will print a 10-digit alphanumeric string with combination of uppercase and lower case letters.

import secrets

num = secrets.randbelow(10)

print(num)

output: randomly prints a number below given range

import secrets num = secrets.randbits(3) print(num)

output: This will print a random number of given bit

Tokens

To generate a more complex random string use token_hex(bytes)

import secrets

token = secrets.token_hex(16)

print(token)

More secure string generation with os.urandom

import os

os.urandom(8)

output: It will give an 8-byte system random number. [sample: 'xcfx8bPWxa7xdfx01' ]

import os, binascii

output = os.urandom(8)

hex = binascii.hexlify(output)

print (hex)

output: It will give the hex value. [sample: 25d6f3739e32cbf7]

secret module generates more secure random and it is available in python 3.x.

If you are interested to learn Python and to become an Python Expert? Then check out our Python Certification Training Course at your near Cities.

Python Course ChennaiPython Course BangalorePython Course DallasPython Course Newyork

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!