I am making a program where the user enters an integer that corresponds to a grade. I want these values to be added to a list that is later printed, in addition to calculating their average. While developing the function, I got stuck with handling data types and calculating the average.
What modification could you make?
def promedio_calificaciones():
valores = []
while True:
valor = int(input("Calificación: "))
if valor == 0:
break
else:
valores.append(valor)
average = valores / len(valores)
print("Tu promedio es de:",average)
print(valores)
Copying your code a bit and without much modification I managed to do something:
Copy and paste, once you call the function and add values to the list it uses a for to add the values and then average with their length.
sum
and functionslen
without having to useloops
. With yousum
add all the elements of the list obtaining the total and with you obtain the totallen
number of elements in the list. Dividing this sum by the elements you have the average oraverage
.try
except
to handle the error when a user enters a number. eg when inserting a letter.else
. In case you insert a 0 you do abreak
to exit the loop. This could be called a guard clause at the basic level. If you enter a 0 it no longer goes into theelse
or, which would be the same, it no longer follows the loop code, so you don't need thatelse
.Code:
Example output:
I offer you a modified code. You will be able to enter grades unlimitedly until loading the zero where the average and a list with all the grades that were loaded will be displayed on the screen.