Storing values of variables within the while function

Asked

Viewed 410 times

2

In an exercise I answered with this code:

qntd_alunos = int(input("Digite a quantidade de alunos: "))
qnt = 0
while qnt <= qntd_alunos-1:
    MB1 = float(input("Digite a média do primeiro bimestre: "))
    MB2 = float(input("Digite a média do segundo bimestre: "))
    media_semestral = (MB1 + MB2) / 2
    if media_semestral >= 7:
        print("Você foi aprovado")
        print("Sua média semestral é: ", media_semestral)
    else:
        print("Sua média semestral é: ", media_semestral)
    qnt = qnt+1
    if qnt == 1:
        print(qnt, "aluno já recebeu sua média, faltam", qntd_alunos - qnt)

    else:
        print(qnt, "alunos já receberam suas médias, faltam", qntd_alunos - qnt)

This code calculates the half-yearly average of each student in the class, sending a message only to the approved, until the last student arrives there the program closes.

What the next exercise asks to transform this code and make it calculate the overall average of the entire class after all the individual averages are typed the only way I found to do this was to store the sum of ALL media_semestral in ONE variable only and dividing this variable by quantidade_alunos. but I couldn’t find a way to create this variable efficiently.

1 answer

1


This is the way, there’s no magic.

qntd_alunos = int(input("Digite a quantidade de alunos: "))
qnt = 0
media_geral = 0
while qnt <= qntd_alunos-1:
    MB1 = float(input("Digite a média do primeiro bimestre: "))
    MB2 = float(input("Digite a média do segundo bimestre: "))
    media_semestral = (MB1 + MB2) / 2
    media_geral += media_semestral
    if media_semestral >= 7:
        print("Você foi aprovado")
        print("Sua média semestral é: ", media_semestral)
    else:
        print("Sua média semestral é: ", media_semestral)
    qnt = qnt+1
    if qnt == 1:
        print(qnt, "aluno já recebeu sua média, faltam", qntd_alunos - qnt)

    else:
        print(qnt, "alunos já receberam suas médias, faltam", qntd_alunos - qnt)
print("Média geral ", media_geral / qntd_alunos)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Wooow...was just that. I was trying for it after the function or even before(???) but just put in XD, thank you very much...was just that same.

Browser other questions tagged

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