我需要用户输入成绩(A,B,C ......) 然后我可以使用它转换为4,3,2,1,0并找到GPA
def grade(ge):
grade = ['A','B','C', 'D', 'F']
getitem(grade);
if grade == 'A': grade = 4;
elif grade == 'B': grade = 3;
elif grade == 'C': grade = 2;
elif grade == 'D': grade = 1;
elif grade == 'F': grade = 0;
else:
print 'error'
total=0
for a in ge:
total=grade+total;
GPA=total/8;
print 'GPA = ', GPA
答案 0 :(得分:1)
AdPlayer
所需要的只是def list_of_grades(lst):
grades = ['A','B','C','D','F']
scores = [4,3,2,1,0]
if any(lst) not in grades:
return "Cannot convert"
lst_grades = [scores[grades.index(l)] for l in lst]
return sum(lst_grades)/len(lst_grades)
是一个等级列表,例如lst
答案 1 :(得分:1)
def convert_grades(grades):
total=0
for g in grades:
if g == 'A': score = 4
elif g == 'B': score = 3
elif g == 'C': score = 2
elif g == 'D': score = 1
elif g == 'F': score = 0
else:
print("Can't convert grade '%s'") % (g)
break
total+=score
GPA=total/len(grades)
return(GPA)
lowgrades = ['C','D','A', 'C', 'B']
highgrades = ['A','A','A', 'B', 'A']
print("GPA: %s") % (convert_grades(lowgrades))
print("GPA: %s") % (convert_grades(highgrades))
答案 2 :(得分:0)
虽然@fugu的答案看起来最接近你想要的,你也可以使用字典或通过使用单个列表摆脱if..elif
。此外,如果您将8更改为len(ge)
,则此函数将适用于任何长度的输入。
def get_grade(ge):
#using a dictionary
grade_values={'A':4,'B':3,'C':2, 'D':1, 'F':0}
total=0
for a in ge:
if a in grade_values:
total=grade_values[a]+total;
else:
print('error')
break # or remove this line to keep calculating
GPA=total/len(ge)
print('GPA = '+str(GPA))
# or use a single list, this list contains the valid input values in order
grade_def = ['A','B','C', 'D', 'F']
total=0
for a in ge:
try:
# grade_def.index(a) returns the location or an error if not found
total=len(grade_def)-1-grade_def.index(a)+total;
except:
print('error')
break
GPA=total/len(ge)
print( 'GPA = '+str(GPA)) #same output as the first example
get_grade(['A','C','C','B','A','A','D','A'])
get_grade(['A','C','C','B','A','A','D','Q']) # will print an error