Random Numbers in Python
Python defines a set of functions that are used to generate or manipulate random numbers through the random module.
Functions in the random module rely on a pseudo-random number generator function random(), which generates a random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any application requiring a random number generation.
Example of Random Number in Python
Generating random number list in Python using random().
Different ways to Generate a Random Number in Python
Method 1: Generating random number list in Python choice()
The choice() is an inbuilt function in the Python programming language that returns a random item from a list, tuple, or string.
Method 2: Generating random number list in Python randrange(beg, end, step)
The random module offers a function that can generate random numbers from a specified range and also allows room for steps to be included, called randrange().
A random number from list is : 4 A random number from range is : 41
Method 3: Generating random number list in Python using seed()
The seed function is used to save the state of a random function so that it can generate some random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator. For the first time when there is no previous value, it uses the current system time.
A random number between 0 and 1 is : 0.510721762520941 The mapped random number with 5 is : 0.6229016948897019 The mapped random number with 7 is : 0.32383276483316237 The mapped random number with 5 is : 0.6229016948897019 The mapped random number with 7 is : 0.32383276483316237
Method 4: Generating random number list in Python using shuffle()
It is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is in place.
Original list : ['A', 'B', 'C', 'D', 'E'] After the first shuffle : ['A', 'B', 'E', 'C', 'D'] After the second shuffle : ['C', 'E', 'B', 'D', 'A']
Method 5: Generating random number list in Python using uniform()
This function is used to generate a floating point random number between the numbers mentioned in its arguments. It takes two arguments, lower limit(included in generation) and upper limit(not included in generation).
The list before shuffling is : 1 4 5 10 2 The list after shuffling is : 2 1 4 5 10 The random floating point number between 5 and 10 is : 5.183697823553464
Please Login to comment...