This happens because of the order in which things are done (and it could be detected by making a table test).
First you add the student in the dictionary:
alunos[nome]=[notas]
Then you check if this student is in the dictionary:
if nome in alunos:
That is, this if
will always be true, because the student you are checking has already been added in the previous row.
What you should do is register the student only if it does not exist in the dictionary (that is, within the else
):
def adicionar_aluno ( alunos , nome , notas ):
if nome in alunos:
return 'já cadastrado'
else:
alunos[nome] = [notas]
return alunos
Although the requirements say you should always return the dictionary, then just modify the condition to only add the student if it does not exist:
def adicionar_aluno ( alunos , nome , notas ):
if nome not in alunos:
alunos[nome] = [notas]
return alunos
That is, if the student does not exist in the dictionary, add (note not in
, that checks if the student is not in the dictionary). If the student already exists, you don’t need to do anything (so you don’t even need the else
).
At the end return the dictionary. If it entered the if
, he will have the new student. If he has not entered the if
, will be returned without modification.
I just found it strange that its function returns a message or the dictionary itself. Perhaps it is better to return True
or False
, indicating whether or not the student was registered. No need to return the dictionary itself because it is modified within the function:
alunos = dict()
def adicionar_aluno ( alunos , nome , notas ):
if nome in alunos:
return False
else:
alunos[nome] = [notas]
return True
nome = input('nome: ')
nota = float(input('nota: ' ))
if adicionar_aluno(alunos, nome, nota):
print(f'aluno {nome} adicionado')
else:
print(f'aluno {nome} já cadastrado')
Thank you very much guy, gave a light here on my problem, I’m starting in language and then some things are kind of confusing, obg!
– w_yll