random.seed() function can help save the state of random functions. Thus, by using seed(), these random functions can generate the same numbers on multiple code executions.
Example 1
Example 1 shows how to use random.seed() and how it impacts the generated numbers.
Note that, random.random() generates a floating point number in the range 0.0 <= X < 1.0.
# importing random module
import random
# set seed - time 1
random.seed(235)
# generate a floating point number - time 1
Generated_number_1 = random.random()
print("Floating Number - time 1 - with seed(235): \n", Generated_number_1 )
# set seed - time 2
random.seed(235)
# generate a floating point number - time 2
Generated_number_2 = random.random()
print("Floating Number - time 2 - with seed(235): \n", Generated_number_2 )
The following is the output. It shows that they generate the same random number because there is a random.seed(235).
Floating Number - time 1 - with seed(235): 0.34681819919543666 Floating Number - time 2 - with seed(235): 0.34681819919543666
Example 2
Example 2 adds time 3, which does not have a random.seed(). Thus, by comparing these 3 times, we can see the difference between with random.seed() and without random.seed().
Note that, random.randint() generates integer numbers in the range you specify.
# importing random module
import random
# set seed - time 1
random.seed(123)
# generate an integer - time 1
Generated_number_1 = random.randint(2, 90)
print("Integer Number - time 1 - with seed(123): \n", Generated_number_1 )
# set the same seed - time 2
random.seed(123)
# generate an integer - time 2
Generated_number_2 = random.randint(2, 90)
print("Integer Number - time 2 - with seed(123): \n", Generated_number_2 )
# generate an integer - time 3 - no seed
Generated_number_3 = random.randint(2, 90)
print("Integer Number - time 3 - no seed: \n", Generated_number_3 )
The following is the output, which shows the differences between 3 different times.
It is worth noting that random.seed() does not set seed for time 3, even though random.randint() is in the same Python code block as times 1 and 2.
Integer Number - time 1 - with seed(123): 8 Integer Number - time 2 - with seed(123): 8 Integer Number - time 3 - no seed: 36
Further Reading
The following are two tutorials about generating random numbers using NumPy.