Python Random – random() Function
There are certain situations that involve games or simulations which work on non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications:
- Creating pseudo-random numbers on Lottery scratch cards
- reCAPTCHA on login forms uses a random number generator to define different numbers and images
- Picking a number, flipping a coin, throwing of a dice related games required random numbers
- Shuffling deck of playing cards
In Python, random numbers are not generated implicitly; therefore, it provides a random module in order to generate random numbers explicitly. random module in Python is used to create random numbers. To generate a random number, we need to import a random module in our program using the command:
import random
There are various functions associated with the random module are:
- random()
- randrange()
- seed()
- randint()
- uniform()
- choice()
- shuffle()
and many more. We are only demonstrating the use of random() function.
1. random.random() function generates random floating numbers in the range[0.1, 1.0). (See the opening and closing brackets, it means including 0 but excluding 1). It takes no parameters and returns values uniformly distributed between 0 and 1.
Syntax : random.random()
Parameters : This method does not accept any parameter.
Returns : This method returns a random floating number between 0 and 1.
Example 1: Python random.random() method example
Python3
# Python3 program to demonstrate # the use of random() function . # import random from random import random # Prints random item print (random()) |
Output:
0.41941790721207284
or
Python3
# Python3 program to demonstrate # the use of random() function . import random # Prints random item print (random.random()) |
Output: 0.059970593824388185
Note: Every time you run this program, it will give a different answer.
Example 2: Creating a list of random numbers in Python using random() function
Python3
# Python3 program to demonstrate # the use of random() function . # import random from random import random lst = [] for i in range ( 10 ): lst.append(random()) # Prints random items print (lst) |
Output:
[0.12144204979175777, 0.27614050014306335, 0.8217122381411321, 0.34259785168486445, 0.6119383347065234, 0.8527573184278889, 0.9741465121560601, 0.21663626227016142, 0.9381166706029976, 0.2785298315133211]
2. seed(): This function generates a random number based on the seed value. It is used to initialize the base value of the pseudorandom number generator. If the seed value is 10, it will always generate 0.5714025946899135 as the first random number.
Example 4: Python random.random() seed
Python3
import random random.seed( 10 ) print (random.random()) #Printing the random number twice random.seed( 10 ) print (random.random()) |
Output:
0.5714025946899135 0.5714025946899135
Please Login to comment...