Python random.seed()
Python random.seed()
The random() function is used to generate random numbers in Python. It’s not actually random, but rather pseudo-random. This means these randomly generated numbers can be determined.
The random() function generates numbers for some value. This value is also called the seed value.
How does the seed function work? The seed function is used to save the state of the random function so that it can produce the same random numbers (for a specific seed value) multiple times, on the same machine or on different machines. The seed value is the previous value generated by the generator. For the first time, when there is no previous value, it uses the current system time.
Using the random.seed() Function
Here, we’ll see how to generate the same random numbers every time using the same seed value.
Example 1:
# random module is imported
import random
for i in range(5):
# Any number can be used in place of '0'.
random.seed(0)
# Generated random number will be between 1 to 1000.
Print(random.randint(1, 1000))
Output:
865
865
865
865
865
Example 2:
# importing random module
import random
random.seed(3)
# print a random number between 1 and 1000.
print(random.randint(1, 1000))
# if you want to get the same random number again then,
random.seed(3)
print(random.randint(1, 1000))
# If seed function is not used
# Gives totally unpredictable responses.
print(random.randint(1, 1000))
Output:
244
244
607
When executing the above code, the two print statements above will produce a response of 244, but the third print statement gives an unpredictable response.
Use of random.seed()
- This is used to generate a pseudo-random encryption key. Encryption keys are an important part of computer security. These are secret keys used to protect data from unauthorized access over the internet.
- It facilitates code optimization, where random numbers are used for testing. The output of a code sometimes depends on its input. Therefore, using random numbers to test an algorithm can be complex. Also, a seed function is used to repeatedly generate the same random numbers, simplifying the algorithm testing process.