Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to use random seed() method in Python

Onyejiaku Theophilus Chidalu

Overview

The random.seed() method is used to initialize the pseudo-random number generator. The random module uses the seed valueprovided as a parameter to the random.seed() method as a base to which it will generate a random number in python. When random numbers are used for testing, this method comes in handy as it makes the optimization of codes very easy.

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 random
random.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 random
random.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 random

random.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.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring