Python random seed() Method
The Python random seed() method changes the seed of the random number generator, and can be called before calling other random module functions.
Python random seed() Syntax
Here is the syntax of the seed() method:
import random
random.seed ( [x] )
When we call random.random() to generate a random number, the number generated is random each time. However, when we set the seed in advance using random.seed(x), where x can be any number, such as 10, the random number generated using random() will be the same if it is called first.
Note: seed() is not directly accessible, you need to import the random module and then call the method via the random static object.
Python random seed() Parameters
- x : change the seed seeded of the random number generator. if you don’t understand how it works, you don’t have to set the seed specifically, Python will choose it for you.
Python random seed() Return Value
This function has no return value.
Python random seed() Example#1
The following shows an example of using the seed(() method.
#!/usr/bin/python3
import random
random.seed()
print ("Generate random number using default seed:", random.random())
print ("Generate random number using default seed:", random.random())
random.seed(10)
print ("Generate random number using integer 100 seeds:", random.random())
random.seed(100)
print ("Using integer 10 seeds to generate random numbers:", random.random())
random.seed("apidemos",2)
print ("Using string seeds to generate random numbers: ", random.random())
Output:
Python random seed() Example#2
#!/usr/bin/python3
import random
random.seed(30)
# 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(30)
print(random.randint(1, 1000))
Output: