为什么这个基本的GPA计算器会返回KeyError?

时间:2016-07-25 07:02:46

标签: python list

Grade1 = input ('Grade for Class 1?')
Grade2 = input ('Grade for Class 2?')
Grade3 = input ('Grade for Class 3?')
Grade4 = input ('Grade for Class 4?')

Grades = (str(Grade1), str(Grade2), str(Grade3), str(Grade4))

def average(numbers):
    total= sum(numbers)
    return total/len(numbers)

def RealGPA(semestergrades):
    PointValues = {'A+': 4.2, 'A':4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C':2.0, 'C-': 1.7, 'D+': 1.3, 'D': 1.0, 'D-': 0.7, 'F': 0.00}
    PointsEarned= []
    for Grade in Grades:
        Values=(PointValues[Grades])
        PointsEarned.append(Values)
return average(PointsEarned)

print (RealGPA(Grades))

它表示“关键错误:('A','A','A','A')如果你为所有输入键入A--这很奇怪,因为'A'存在于PointValues中。我输错了吗?

3 个答案:

答案 0 :(得分:0)

PointValues[Grades](str(Grade1), str(Grade2), str(Grade3), str(Grade4))词典中查找元组PointValues,这显然会生成KeyError

也许你的意思是PointValues[Grade]

答案 1 :(得分:0)

一个简单的拼写错误 - 你写的是gawk -i inplace而不是Grades

还添加了一些其他更改(请参阅PEP8样式指南):

Grade

答案 2 :(得分:0)

有一个小错字。此Values=(PointValues[Grades])Values=(PointValues[Grade])。而且函数名和变量名也应该都是小写的。