How to avoid code repetition to average a variable amount of banknotes

Asked

Viewed 315 times

-1

I created a simple script to make it easier to average students.

The problem is that I might need a while to repeat the code. I wanted to make sure that when I finished displaying a student’s average, I would come back and ask again what the grades would be.

Code:

print('----------------MÉDIA DO ALUNO----------------')
qn = int(input('Quantas notas são? [2,3,4,5]: '))
d = int(input('As notas serão dividas por quanto? '))
if qn == 2:
    n1 = float(input('Qual a primeira nota? '))
    n2 = float(input('Qual a segunda nota? '))
    m1 = n1 + n2
    mm = m1 / d
    print('A média é {:.2f}'.format(mm))
if qn == 3:
    n1 = float(input('Qual a primeira nota? '))
    n2 = float(input('Qual a segunda nota? '))
    n3 = float(input('Qual a terceira nota? '))
    m1 = n1+n2+n3
    mm = m1 / d
    print('A média é {:.2f}'.format(mm))
if qn == 4:
    n1 = float(input('Qual a primeira nota? '))
    n2 = float(input('Qual a segunda nota? '))
    n3 = float(input('Qual a terceira nota? '))
    n4 = float(input('Qual a quarta nota? '))
    m1 = n1+n2+n3+n4
    mm = m1 / d  
    print('A média é {:.2f}'.format(mm))
if qn == 5:
    n1 = float(input('Qual a primeira nota? '))
    n2 = float(input('Qual a segunda nota? '))
    n3 = float(input('Qual a terceira nota? '))
    n4 = float(input('Qual a quarta nota? '))
    n5 = float(input('Qual a quinta nota? '))
    m1 = n1+n2+n3+n4+n5
    mm = m1 / d 
    print('A média é {:.2f}'.format(mm))
  • Welcome Caio, read this reply I believe that’s what you want.

2 answers

3

Your code is very repetitive. If I were you I would use two while, in the first I would put a stop feature, such as: "Type quit' to finish the program, ex:

print("Digite ‘sair’ para finalizar o programa")

while True:

    quantidade_notas = input("Digite a quantidade de notas que serão inseridas:")
    if quantidade_notas == "sair":
        break
        # codigo

Already inside that eh would put a repeat the amount of notes that would be inserted, ex:

while True:
    quantidade_notas = input("Digite a quantidade de notas que serão inseridas:")

    if quantidade_notas == "sair":
        break

    while quantidade_notas > 0:
        # codigo de print e scan
        quantidade_notas = quantidade_notas -1

1


Your code is too repetitive. The idea to eliminate this repetition is to identify what repeats and what varies, and put it all into one loop. In this case, what varies is the number of notes, but there is a pattern that repeats: I read the notes, sum and calculate the average.

Another detail is that having the amount of notes, it makes no sense to have another number to divide. For example, if I have 3 notes, does it make sense to divide their sum by 10 to calculate the average? No, I divide by 3, which is the number of notes (assuming you want the arithmetic mean - if it were weighted average, for example, you would need to read the weights, but the code indicates that you probably want the arithmetic mean itself). That is, the variable d of your code is not required.

And if you want to repeat this process over and over again, put it all inside a loop. Anyway, one way to solve it is:

print('----------------MÉDIA DO ALUNO----------------')
while True:
    try:
        quantidade = int(input('Quantas notas são? [2,3,4,5] (0 para encerrar): '))
        if quantidade == 0:
            break

        if 2 <= quantidade <= 5:
            notas = []
            for i in range(quantidade):
                notas.append(float(input('Qual a {}ª nota? '.format(i + 1))))
            print('A média é {:.2f}'.format(sum(notas) / len(notas)))
        else:
            print('Quantidade de notas deve estar entre 2 e 5')
    except ValueError:
        print('Não foi digitado um número válido')

while True is a loop infinite: it executes "forever", or until it is interrupted (either by break, either by some mistake).

I included a stop condition: when the amount is zero, it comes out of the loop (the break interrupts the while).

There is also a block try/except capturing the ValueError, which is the exception that occurs int or float cannot convert what was typed to number (for example, if the user types "xyz", will give this error and fall into the block except). In this case, I just print a message and go back to the beginning of loop, asking again to enter the amount.

Then I check if the quantity is between 2 and 5, which seem to be the valid options. If it is, I proceed with another loop to read the notes. Here I use a range to iterate by the numbers. In this case, range(quantidade) creates the sequence of the numbers from zero to quantidade - 1. Then I read the notes and I’ll keep it on the list notas.

Incidentally, this for is what I mentioned at the beginning: identify what varies and what repeats to create the loop. What varies is the amount of notes to be read, and this is controlled by range. What repeats is what’s inside the for: reading a note.

Finally, I display the average. For this I use sum, adding up the values of the list, and len, which returns the size of the list (I could also have used the variable itself quantidade).

After printing the average, it goes back to the beginning of the while, that is, asks to type the amount of notes again.


The for can also be exchanged for a comprehensilist on, much more succinct and pythonic:

if 2 <= quantidade <= 5:
    notas = [ float(input('Qual a {}ª nota? '.format(i + 1))) for i in range(quantidade) ]
    print('A média é {:.2f}'.format(sum(notas) / len(notas)))

Browser other questions tagged

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