- Python Random seed() Function
- 1. Quick Examples of random.seed() Function
- 2. Random seed() Function
- 2.1 Syntax of random.seed()
- 2.2 Parameters of random.seed()
- 2.3 Return Value
- 3. Usage of random.seed() Function
- 4. Set seed value None & Get the Different Random Numbers
- 5. Use Python seed() function with Random.randint()
- 6. Conclusion
- Related Articles
- You may also like reading:
- Python 3: Генерация случайных чисел (модуль random)¶
- random.random¶
- random.seed¶
- random.uniform¶
- random.randint¶
- random.choince¶
- random.randrange¶
- random.shuffle¶
- Вероятностные распределения¶
- Примеры¶
- Генерация произвольного пароля¶
- Ссылки¶
Python Random seed() Function
Python provides seed() function from the random module that is used to set the seed value to generate pseudo-random numbers. A pseudo-random number is a number that is kind of random, but they are not really random numbers. By setting a seed value with this method, you can ensure that the sequence of random numbers generated by the random module will be the same every time you run your program.
The random seed is a numerical value that repeats pseudo-random numbers in Python. The value in the random seed saves the state of randomness. For example, If we call the seed function with seed value ‘1’ multiple times, the computer generates the same random numbers. When the value is not mentioned in the random seed, then the computer will use the current system time in seconds or milliseconds as a seed value to generate a different set of random numbers.
1. Quick Examples of random.seed() Function
If you are in a hurry, below are some quick examples of random.seed() function.
# Quick examples of random.seed() function # Example 1: Initialize the seed() with 3 & get the random numbers random.seed(3) print(random.random()) # Example 2: Initialize the seed() with 0 & get the random numbers random.seed(0) print(random.random()) # Example 3: Initialize the seed() with None & get the random numbers random.seed() print(random.random()) # Example 4: Initialize the seed() with 5 & get the random integers random.seed(5) print(random.randint(10, 20))
2. Random seed() Function
The Python seed() function is used to initialize the random number generator by providing a seed value that repeats the pseudo-random numbers. If we use the same seed value multiple times to initialize the random number generator, we get the same random numbers.
2.1 Syntax of random.seed()
Following is the syntax of the random.seed().
# Syntax of random.seed() random.seed(a, version)
2.2 Parameters of random.seed()
- a: (Optional) Is a seed value is used to provide seed value to a random number generator. The default value is None. If it is None random number generator uses the current system time. If it is an integer we can use it directly and if not it needs to be converted into an integer.
- version: An integer is used to specify how to convert a in a integer. Default value is 2.
2.3 Return Value
It returns nothing, it just specifies the seed value.
3. Usage of random.seed() Function
Using the Python random.seed() function we can provide seed value to customize the random number generator, by default it uses the current system time.
In the below example, first, we have initialized the seed() function with a seed value(4) and then call the random() function to get the random value.
# Import random module import random # Initialize the seed() with 3 & get the random numbers random.seed(3) print("Random number of seed value 3:") print(random.random()) print(random.random())
When you run the above code another time you get the same set of random numbers as the above.
Now, change the seed value and run the same example again. Notice that the generated random values changed.
# Import random module import random # Initialize the seed() with 0 & get the random numbers random.seed(0) print("Random number of seed value 0:") print(random.random()) print(random.random())
When you run the above code another time you get the same set of random numbers as the above.
4. Set seed value None & Get the Different Random Numbers
We can get different random numbers for each run by calling the seed() function with out any argument. By executing multiple times, we get the different random numbers.
# Import random module import random # Initialize the seed() with None & get the random numbers random.seed() print("Random number of seed value None:") print(random.random()) print(random.random()) print(random.random()) # Output: # Random number of seed value None: # 0.08325080335264412 # 0.2902867023198895 # 0.0310261895700632
When you run the above code another time you get a different set of random numbers than the above.
5. Use Python seed() function with Random.randint()
Use the random.seed() function with random.randint() function and get the repeated random numbers for multiple executions. randint() function is another function of the random module in Python which is used to generate the random number between the specified range of integers.
Let’s set the seed() function with the seed value and call the randint() to get the same random integer of the specified range.
# Import random module import random # Initialize the seed() with 5 & get the random integers random.seed(5) print("Random integer of seed value 5:") print(random.randint(10, 20)) print(random.randint(10, 20)) # Output: # Random integer of seed value 5: # 19 # 14
When you run the above code another time you get the same set of random numbers as the above.
6. Conclusion
In this article, I have explained Python random.seed() function syntax, parameters, and usage of how to initialize the random number generator with examples. By setting a seed value with this method, you can ensure that the sequence of random numbers generated by the random module will be the same every time you run your program.
Related Articles
- Random String Generation with Letters and Digits in Python
- Python random.randint() with Examples
- Python Random uniform() Function
- Python Random Module Methods Explained
- Generate Random Integers Between 0 and 9 in Python
- Python random.sample() With Examples
- Shuffle List in Python with Examples
- Python Random randrange() Function
- Generate Random Float Numbers in Python
- Python random.choice() function
- Python random.random() function
You may also like reading:
Python 3: Генерация случайных чисел (модуль random)¶
Python порождает случайные числа на основе формулы, так что они не на самом деле случайные, а, как говорят, псевдослучайные [1]. Этот способ удобен для большинства приложений (кроме онлайновых казино) [2].
[1] | Википедия: Генератор псевдослучайных чисел |
[2] | Доусон М. Программируем на Python. — СПб.: Питер, 2014. — 416 с.: ил. — 3-е изд |
Модуль random позволяет генерировать случайные числа. Прежде чем использовать модуль, необходимо подключить его с помощью инструкции:
random.random¶
random.random() — возвращает псевдослучайное число от 0.0 до 1.0
random.random() 0.07500815468466127
random.seed¶
random.seed() — настраивает генератор случайных чисел на новую последовательность. По умолчанию используется системное время. Если значение параметра будет одиноким, то генерируется одинокое число:
random.seed(20) random.random() 0.9056396761745207 random.random() 0.6862541570267026 random.seed(20) random.random() 0.9056396761745207 random.random() 0.7665092563626442
random.uniform¶
random.uniform(, ) — возвращает псевдослучайное вещественное число в диапазоне от до :
random.uniform(0, 20) 15.330185127252884 random.uniform(0, 20) 18.092324756265473
random.randint¶
random.randint(, ) — возвращает псевдослучайное целое число в диапазоне от до :
random.randint(1,27) 9 random.randint(1,27) 22
random.choince¶
random.choince() — возвращает случайный элемент из любой последовательности (строки, списка, кортежа):
random.choice('Chewbacca') 'h' random.choice([1,2,'a','b']) 2 random.choice([1,2,'a','b']) 'a'
random.randrange¶
random.randrange(, , ) — возвращает случайно выбранное число из последовательности.
random.shuffle¶
random.shuffle() — перемешивает последовательность (изменяется сама последовательность). Поэтому функция не работает для неизменяемых объектов.
List = [1,2,3,4,5,6,7,8,9] List [1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle(List) List [6, 7, 1, 9, 5, 8, 3, 2, 4]
Вероятностные распределения¶
random.triangular(low, high, mode) — случайное число с плавающей точкой, low ≤ N ≤ high . Mode — распределение.
random.betavariate(alpha, beta) — бета-распределение. alpha>0 , beta>0 . Возвращает от 0 до 1.
random.expovariate(lambd) — экспоненциальное распределение. lambd равен 1/среднее желаемое. Lambd должен быть отличным от нуля. Возвращаемые значения от 0 до плюс бесконечности, если lambd положительно, и от минус бесконечности до 0, если lambd отрицательный.
random.gammavariate(alpha, beta) — гамма-распределение. Условия на параметры alpha>0 и beta>0 .
random.gauss(значение, стандартное отклонение) — распределение Гаусса.
random.lognormvariate(mu, sigma) — логарифм нормального распределения. Если взять натуральный логарифм этого распределения, то вы получите нормальное распределение со средним mu и стандартным отклонением sigma . mu может иметь любое значение, и sigma должна быть больше нуля.
random.normalvariate(mu, sigma) — нормальное распределение. mu — среднее значение, sigma — стандартное отклонение.
random.vonmisesvariate(mu, kappa) — mu — средний угол, выраженный в радианах от 0 до 2π, и kappa — параметр концентрации, который должен быть больше или равен нулю. Если каппа равна нулю, это распределение сводится к случайному углу в диапазоне от 0 до 2π.
random.paretovariate(alpha) — распределение Парето.
random.weibullvariate(alpha, beta) — распределение Вейбулла.
Примеры¶
Генерация произвольного пароля¶
Хороший пароль должен быть произвольным и состоять минимум из 6 символов, в нём должны быть цифры, строчные и прописные буквы. Приготовить такой пароль можно по следующему рецепту:
import random # Щепотка цифр str1 = '123456789' # Щепотка строчных букв str2 = 'qwertyuiopasdfghjklzxcvbnm' # Щепотка прописных букв. Готовится преобразованием str2 в верхний регистр. str3 = str2.upper() print(str3) # Выведет: 'QWERTYUIOPASDFGHJKLZXCVBNM' # Соединяем все строки в одну str4 = str1+str2+str3 print(str4) # Выведет: '123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' # Преобразуем получившуюся строку в список ls = list(str4) # Тщательно перемешиваем список random.shuffle(ls) # Извлекаем из списка 12 произвольных значений psw = ''.join([random.choice(ls) for x in range(12)]) # Пароль готов print(psw) # Выведет: '1t9G4YPsQ5L7'
Этот же скрипт можно записать всего в две строки:
import random print(''.join([random.choice(list('123456789qwertyuiopasdfghjklzxc vbnmQWERTYUIOPASDFGHJKLZXCVBNM')) for x in range(12)]))
Данная команда является краткой записью цикла for, вместо неё можно было написать так:
import random psw = '' # предварительно создаем переменную psw for x in range(12): psw = psw + random.choice(list('123456789qwertyuiopasdfgh jklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM')) print(psw) # Выведет: Ci7nU6343YGZ
Данный цикл повторяется 12 раз и на каждом круге добавляет к строке psw произвольно выбранный элемент из списка.