the following code receives from user some grades on coursers that he took in previous semester and their weights. when user is done he will type "done" instead the grade. I need to complete a code that compute weighted average and store it in variable res rounded to hundredths.
weighted average = sum(grade*points)/sum(points)
here is what I tried so far:
grade = input("enter your grade: ")
points = input("enter the points: ")
#innitialise the variables before while loop:
sum_grade = 0
sum_points = 0
#write a while loop that terminates when the user enters "done" to grade variable
#calculate the grade to variable res in this format XX.XX
while grade != "done":
sum_grade += int(grade)
sum_points += int(points)
grade = input("enter your grade: ")
points = input("enter the points: ")
continue
else:
break
res = sum_grade*sum_points / sum_points
res ="%.2f"%float
Thank you in advanced :-)
You have the right pieces. You just need to put them in the right order.
Try this code:
sum_grade = 0
sum_points = 0
while True:
grade = input("enter your grade: ")
if grade == "done": break # done
points = int(input("enter the points: "))
grade = int(grade)
sum_grade += grade * points
sum_points += points
res = sum_grade / sum_points
res ="%.2f"%res
print(res)
Output
enter your grade: 10
enter the points: 10
enter your grade: 50
enter the points: 1
enter your grade: done
13.64
You can either use Numpy
as following :
import numpy as np
np.average(sum_grade, axis=1, weights=sum_points)
or by modfying your code as follow :
sum_grade += int(grade*points)
and
res = sum_grade / sum_points
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.