How to use random seed() method in Python
Overview
The random.seed() method is used to initialize the pseudo-random number generator. The random module uses the random.seed() method
Syntax
random.seed(a, version)
Parameter values
| Parameter | Description |
|---|---|
a |
This is optional. It is the seed value required to generate a random number. This value should always be an integer. The default value is none, and in this case, the generator uses the current system time. |
version |
This is an integer value. It is required to specify how to change the parameter (a) into an integer. The default value is 2. |
Example 1: How to use the random.seed() method
Now, let us generate a random number setting the seed value as 4.
import randomrandom.seed(4)print(random.random())
Explanation
- Line 1: we imported the random module.
- Line 2: we used the
random.seed()method by setting the seed value to 4. - Line 3: we printed the output.
Example 2: Using both the seed value and the version parameter
Now, let us generate a random number by passing a seed value (5) and a version (3).
import randomrandom.seed(5.3)print(random.random())
Example 3: Using the same seed value twice
Now, let us see what happens when we use the same seed value twice.
import randomrandom.seed(5)print(random.random())random.seed(5)print(random.random())
As can be seen from the program above, using the same seed value twice will return the same random number twice.