As for the question.
No, you are not using the function correctly random.randint()
and the other answers also do not make a correct use of the function.
How are enrolling students in a dictionary fatally function randint()
will draw a license plate number that has already been used so there will be a key collision that implies the loss of a registered license plate.
To solve the problem do not use randint()
, the problem is more complex than the use case which was designed.
What you can do is create a list with the range of values to be used as the number plate and then shuffle that list with the function random.shuffle()
and with a generating function go extracting one by one, when asked a number of matricula with the built-in function next():
Example:
from random import shuffle
def matricula_gen():
matriculas = list(range(100, 1000)) #Cria uma lista com faixa válida de valores de matriculas.
shuffle(matriculas) #Embaralha a lista.
#Enquanto a lista matriculas não estiver vazia...
while len(matriculas) > 0:
yield matriculas.pop(0) #...remove o primeiro elemento de matriculas e o retorna.
numero_de_matricula= matricula_gen() #Cria o gerador de matriculas.
for _ in range(15):
print(next(numero_de_matricula)) #Imprime 15 matriculas de teste.
Inserting into the question code.
The question code presents many problems:
- The function
perguntar()
can be simplified.
- The function
numero_de_matricula()
does not return value and if returned generates duplicate keys.
- In function
inserir_dados()
you are using the function result print()
which is None as key in a dictionary.
- Your options menu is displayed only once.
- The link of activities is not appropriate.
So I made some modifications to make your example functional and embed the answer to your question:
from datetime import date, time, datetime, timedelta
from random import shuffle
menu = """O que deseja realizar?
<I> Para inserir um usuário:
<P> Para pesquisar um usuário:
<E> Para excluir um usuário:
<L> Para listar um usuário:
<S> Para sair: """
def matricula_gen():
matriculas = list(range(100, 1000))
shuffle(matriculas)
while len(matriculas) > 0:
yield matriculas.pop(0)
proxima_matricula = matricula_gen()
def perguntar():
return input(menu).upper()
def numero_de_matricula():
return next(proxima_matricula)
def inserir_dados(dicionario):
try:
dicionario[numero_de_matricula()] = [
input('Digite o login: ').upper(),
input('Digite o nome: ').upper(),
input('Digite a última data de acesso: '),
input('Digite a última estação acessada: ').upper()]
except StopIteration:
print("As matriculas estão esgotadas.")
return False
return True
usuarios = {}
while True:
opcao = perguntar()
if opcao == 'I':
if inserir_dados(usuarios):
print('Usuário cadastrado com sucesso. ')
else:
print('Usuário não pode ser cadastrado. ')
elif opcao == 'P':
pass
elif opcao == 'E':
pass
elif opcao == 'L':
pass
else:
print('Opção inválida.')
In function
numero_de_matricula
you did not return the selected value, only assigned in the variablenum_matricula
that is not used. Make areturn num_matricula
in this function, because without it the return of the function will always beNone
, which may justify this value as a dictionary key.– Woss