我有一个我已经完成的程序并且它可以工作,但我在列表上遇到了很多困难。我想将成绩存储在列表中,并且仍然以相同的方式运行程序。 python程序应该可以获得学生的成绩,给他们个人GPA,然后在程序完全终止后输出最终的gpa级别。
gpa_entire_class = 0
count_entire_class = 0
def GetName():
name = raw_input ("Enter the student's name of '***' to terminate ")
if name == '***':
print "PROGRAM TERMINATED ON REQUEST"
print "The GPA for all entered grades is %.2f" %(CalcGPA(gpa_entire_class, count_entire_class))
exit(0)
else:
return name
def getgrades():
count = 0
totalgpa = 0
grade = raw_input("Enter a grade or '*' to terminate: ")
while grade!='*':
if grade == 'A' or grade == 'a':
totalgpa = totalgpa + 4
count = count + 1
elif grade == 'B' or grade == 'b':
totalgpa = totalgpa + 3
count = count + 1
elif grade == 'C' or grade == 'c':
totalgpa = totalgpa + 2
count = count + 1
elif grade == 'D' or grade == 'd':
totalgpa = totalgpa + 1
count = count + 1
elif grade == 'F' or grade == 'f':
totalgpa = totalgpa + 0
count = count + 1
else:
print "ILLEGAL GRADE ENTERED"
grade = raw_input("Enter a grade or '*' to terminate: ")
return totalgpa, count
def CalcGPA(totalgpa,count):
if count == 0:
GPA = 0
else:
GPA = (totalgpa)*1.0/count
return GPA
def main(name, GPA):
print "The GPA for", name,"is %.2f" %(GPA)
return 0
while True:
name = GetName()
totalgpa, count = getgrades()
GPA= CalcGPA(totalgpa, count)
main(name, GPA)
gpa_entire_class = gpa_entire_class + totalgpa
count_entire_class = count_entire_class + count
答案 0 :(得分:0)
对于成绩,您可以从dict
开始:
grades_to_gpa = {'a': 4, 'b': 3, 'c': 2, 'd': 1, 'f': 0}
然后在get_gpa
def get_gpa():
gpa_list = []
grade = raw_input("Enter a grade or '*' to terminate: ")
while grade != '*':
try:
points = grades_to_gpa[grade.lower()]
gpa_list.append(points)
except KeyError:
print "Illegal grade"
grade = raw_input("Enter a grade or '*' to terminate: ")
return gpa_list
并在main
def main():
gpa_list = get_gpa()
try:
avg_gpa = sum(gpa_list) / (len(gpa_list)*1.0)
except ZeroDivisionError:
avg_gpa = 0.0
print avg_gpa
我遗漏了一些部分,但我认为你应该从这开始就有了一个想法。
小解释
在get_gpa()
的第5行,我们首先使用grade
并将其缩小。因此,无论A
还是a
,我们都会使用a
搜索字典。我们可以使用dictionary[key]
从字典中查找值,这将取代您拥有的if-else
结构。然后我们将该值(从0到4的数字)附加到所有gpas的列表中。
总的来说,我们可以try
除以长度,如果gpa_list
为空,我们会得到ZeroDivisionError
,在这种情况下avg_gpa
是0