Python random() function is used to generate the pseudo-random numbers. It generates numbers for some values called seed values.
How does seed function work?
The seed function stores a random method to generate the same random numbers on multiple code executions on the same or different machines.
The seed value is precious in computer security to pseudo-randomly produce a secure secret encryption key. So using the custom seed value, you can initialize the secure pseudo-random number generator to the extent you need.
Python random seed
The random.seed() is a built-in Python function that initializes the random numbers. The random number generator uses the current system time by default.
If you use the same seed value twice, you get the same output means a random number twice.
Syntax
random.seed(svalue, version)
Parameters
The svalue parameter is optional, and the seed value is needed to generate a random number. The default value is None, and the generator uses the current system time if None.
It is an integer specifying how to convert the svalue parameter into an integer. The default value is 2.
Example
# app.py import random random.seed(10) print(random.random()) random.seed(10) print(random.random())
Output
0.5714025946899135 0.5714025946899135
This example demonstrates that if you use the same seed value twice, you will get the same random number twice.
Let’s see another example in which we generate the same random number many times.
# app.py import random for i in range(5): # Any number can be used in place of '11'. random.seed(11) # Generated random number will be between 1 to 1000. print(random.randint(1, 1000))
Output
464 464 464 464 464
When we supply a specific seed to the random generator, you will get the same numbers every time you execute a program. That is useful when you need a predictable source of random numbers.
It makes optimization of codes easy where random numbers are used for testing. However, the output of the code sometimes depends on the input. So the use of random numbers for testing algorithms can be problematic.
Also, the seed function is used to generate the same random numbers again and again and simplifies the algorithm testing process.
That is it for Python random seed() function.