Python Random - random() Function
The random() function in Python is used to generate a random floating-point number between 0 and 1. It's part of the random module and helps add randomness to your programs, like in games or simulations.
To generate a random number, we need to import the "random module" in our program using the command:
from random import random
Syntax
random()
Parameters: function does not take any parameters.
Example 1: Generating a random number
from random import random
print(random())
Output
0.708371072924057
Explanation: generate different number every time you run this program.
Example 2: Creating List of random numbers
from random import random
li = []
for i in range(4):
li.append(random())
print(li)
Output
[0.958704121933274, 0.6906654116157793, 0.7080091136195106, 0.6164759794476892]
Explanation: creates and prints a list of 4 random float numbers using random().
Random seed() Method
The seed() method in random module is used to set the starting point for generating random numbers.
from random import random, seed
seed(10)
print(random())
Output
0.5714025946899135
Explanation: sets a fixed seed for the random generator and prints the same random float every time it runs.
Related Articles: