Problem to add data to a dictionary

Asked

Viewed 56 times

1

I’m trying to build a function for calculating multi-note averages, but error occurs when I try to pass this data to a dictionary.

The system claims that the class of data that I try to pass is not compatible, but I’ve done it a few times, in other programs, and that didn’t used to happen.

Follows the code:

def Media():

    Notas = {'Total:', 'Maior:', 'Menor:', 'Média:', 'Situação:'}
    
    Valor = 0
    P = 1
    Soma = 0
    c = 0
    
    while True:
        while True:
            N = str(input(f'Digite a {P}° nota: '))
            if N.isnumeric():
                Valor = float(N)
                break
            else:
                print('ERRO! Digite um valor númerico!')
        for c in range(0,1):
            Maior = Menor = Valor
            c += 1
        if Valor >= Maior:
            Notas['Maior:'] = Maior
            P += 1
            Soma += Valor
        elif Valor <= Menor:
            Notas['Menor:'] = Menor
            P += 1
            Soma += Valor
    
    
        R = str(input('Deseja inserir outro valor?' )).upper()
        if R not in 'SN':
            print('Digite uma resposta válida!')
        if R == 'N':
            break


    Media = Soma / P
    if Media < 6:
        Notas['Situação:'] = 'Tá tensa!'
    if Media > 6:
        Notas['Situação:'] = 'Ta tranquila.'
    Notas['Média:'] = Media 
    Notas['Total:'] = P

   print(Notas)


print(30 * '-')
print('CALCULADOR DE MÉDIAS DOS ALUNOS')
print(30 * '-')

print('Um momento que o sistema está iniciando...')
sleep(0.3)

Media()

1 answer

1

This here nay is a dictionary:

Notas = {'Total:', 'Maior:', 'Menor:', 'Média:', 'Situação:'}

In fact you created a set.

What can confuse is that to create set's and dictionaries, keys are used as delimiters. What distinguishes one from the other is the content.

A dictionary contains key-value pairs. Between the key and the respective value there is a :, and between each key-value pair there is a comma. Already a set has only values, all separated by a comma:

sou_um_dicionario = {
    'chave 1' : 'valor 1', # repare nos dois-pontos separando a chave e o valor
    'chave 2' : 'valor 2'
}

print(type(sou_um_dicionario)) # <class 'dict'>

sou_um_set = {
    'valor 1', # não tem dois-pontos, somente vírgulas separandos os valores
    'valor 2'
}

print(type(sou_um_set)) # <class 'set'>

In case, you created a set, since the : are inside the quotes, that is, they are part of the strings that are the values of the set and are not acting like the separators that stand between the key and the value.


If I understand correctly, what you want is something like this:

def media():
    notas = {'maior': float('-inf'), 'menor': float('inf')}
    i = 0
    soma = 0
    while True:
        while True:
            try:
                valor = float(input(f'Digite a {i + 1}° nota: '))
                break
            except ValueError:
                print('ERRO! Digite um valor númerico!')
        if valor > notas['maior']:
            notas['maior'] = valor
        if valor < notas['menor']:
            notas['menor'] = valor
        soma += valor
        i += 1

        while True:
            opcao = input('Deseja inserir outro valor?').upper()
            if opcao not in ['S', 'N']:
                print('Digite uma resposta válida!')
            else:
                break
        if opcao == 'N':
            break

    media = soma / i
    if media < 6:
        notas['situação'] = 'Tá tensa!'
    else:
        notas['situação'] = 'Ta tranquila.'
    notas['media'] = media
    notas['total'] = i

    print(notas)


print(30 * '-')
print('CALCULADOR DE MÉDIAS DOS ALUNOS')
print(30 * '-')

print('Um momento que o sistema está iniciando...')

media()

input already returns a string, so do str(input()) is unnecessary.

I also changed the names of the keys, I saw no reason to have : in them. And I start the highest note with a small value (in this case, "negative infinity"), so any value that is typed will be higher than it, and the first time you test the if, the maior will be updated correctly. The same goes for the lowest grade: if you start it with zero, and only enter values greater than zero, your program says that the lowest grade is zero. Then I start it with a large value ("infinite"), so I guarantee that any value typed will be smaller than it, avoiding this problem.

Your accountant P ended with "1 more", so the average was wrong.

To see the situation, you would only test if the average is less than or greater than 6 (and if it was equal to 6, would be without situation).

And to check if the typed note is a number, I preferred to use a block try and capture the ValueError. This is because there are several characters for which isnumeric returns True but error when converting to float (see here). And as anything can be typed, the most guaranteed is simply try to convert and capture the error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.