Python define um conjunto de funções que são usadas para gerar ou manipular números aleatórios através do módulo aleatório.
Funções no módulo aleatório conte com uma função geradora de números pseudo-aleatórios random() que gera um número flutuante aleatório entre 0,0 e 1,0. Esse tipo específico de função é usado em muitas loterias de jogos ou em qualquer aplicativo que exija geração de números aleatórios.
Vejamos um exemplo de geração de um aleatório número em Python usando o função aleatória().
Pythonimport random num = random.random() print(num)
Saída:
0.30078080420602904Diferentes maneiras de gerar um número aleatório em Python
Existem várias maneiras de gerar números aleatórios em Python usando as funções do módulo aleatório do Python. Vejamos algumas maneiras diferentes.
Gerando um número aleatório usando escolha()
Pitão random.choice() é uma função embutida na linguagem de programação Python que retorna um item aleatório de um lista tupla ou corda .
Python# import random import random # prints a random value from the list list1 = [1 2 3 4 5 6] print(random.choice(list1)) # prints a random item from the string string = 'striver' print(random.choice(string))
Saída:
5
t
Gerando um número aleatório usando randrange()
O módulo random oferece uma função que pode gerar números aleatórios em Python a partir de um intervalo especificado e também permite espaço para a inclusão de etapas chamadas intervalo aleatório() .
Python
# importing 'random' for random operations import random # using choice() to generate a random number from a # given list of numbers. print('A random number from list is : ' end='') print(random.choice([1 4 8 10 3])) # using randrange() to generate in range from 20 # to 50. The last parameter 3 is step size to skip # three numbers when selecting. print('A random number from range is : ' end='') print(random.randrange(20 50 3))
Saída:
A random number from list is : 4
A random number from range is : 41
Gerando um número aleatório usando seed()
Pitão random.seed() A função é usada para salvar o estado de uma função aleatória para que ela possa gerar alguns números aleatórios em Python em múltiplas execuções do código na mesma máquina ou em máquinas diferentes (para um valor inicial específico). O valor inicial é o número do valor anterior gerado pelo gerador. Pela primeira vez, quando não há valor anterior, ele usa a hora atual do sistema.
Python# importing 'random' for random operations import random # using random() to generate a random number # between 0 and 1 print('A random number between 0 and 1 is : ' end='') print(random.random()) # using seed() to seed a random number random.seed(5) # printing mapped random number print('The mapped random number with 5 is : ' end='') print(random.random()) # using seed() to seed different random number random.seed(7) # printing mapped random number print('The mapped random number with 7 is : ' end='') print(random.random()) # using seed() to seed to 5 again random.seed(5) # printing mapped random number print('The mapped random number with 5 is : ' end='') print(random.random()) # using seed() to seed to 7 again random.seed(7) # printing mapped random number print('The mapped random number with 7 is : ' end='') print(random.random())
Saída:
A random number between 0 and 1 is : 0.510721762520941
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
The mapped random number with 5 is : 0.6229016948897019
The mapped random number with 7 is : 0.32383276483316237
Gerando um número aleatório usando shuffle()
O embaralhar() A função é usada para embaralhar uma sequência (lista). Embaralhar significa alterar a posição dos elementos da sequência. Aqui a operação de embaralhamento está em vigor.
Python# import the random module import random # declare a list sample_list = ['A' 'B' 'C' 'D' 'E'] print('Original list : ') print(sample_list) # first shuffle random.shuffle(sample_list) print('nAfter the first shuffle : ') print(sample_list) # second shuffle random.shuffle(sample_list) print('nAfter the second shuffle : ') print(sample_list)
Saída:
Original list :
['A' 'B' 'C' 'D' 'E']
After the first shuffle :
['A' 'B' 'E' 'C' 'D']
After the second shuffle :
['C' 'E' 'B' 'D' 'A']
Gerando um número aleatório usando uniform()
O uniforme() A função é usada para gerar um número aleatório Python de ponto flutuante entre os números mencionados em seus argumentos. São necessários dois argumentos: limite inferior (incluído na geração) e limite superior (não incluído na geração).
Python# Python code to demonstrate the working of # shuffle() and uniform() # importing 'random' for random operations import random # Initializing list li = [1 4 5 10 2] # Printing list before shuffling print('The list before shuffling is : ' end='') for i in range(0 len(li)): print(li[i] end=' ') print('r') # using shuffle() to shuffle the list random.shuffle(li) # Printing list after shuffling print('The list after shuffling is : ' end='') for i in range(0 len(li)): print(li[i] end=' ') print('r') # using uniform() to generate random floating number in range # prints number between 5 and 10 print('The random floating point number between 5 and 10 is : ' end='') print(random.uniform(5 10))
Saída:
The list before shuffling is : 1 4 5 10 2
The list after shuffling is : 2 1 4 5 10
The random floating point number between 5 and 10 is : 5.183697823553464