Random Number Generation in Python Programming

Random number generation is the process of generating a number that cannot be predicted better than by a random chance.

pro_grammer
MindMajix
2 min readNov 6, 2019

--

Image credits: Shutterstock

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.

Code for Random Numer Generation

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

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

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

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

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

Output: It will display 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 )

Output: It will output a list of 4 random characters from string and list. The syntax is random.sample (sequence, length)

Sample output:

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.

Output:

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.

By the following methodologies & code you will achieve a successful random number generation.

If you want to know more about random number generation then click here.

This Article is sourced from: mindmajix

--

--