我试图创建下面参数描述的函数,但我一直得到以下输出值,不知道为什么
输出错误消息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/<username>/Desktop/CS 1110/lab16/lab16.py", line 66, in
letter_grades
if result[k] >= 90:
KeyError: 'wmw2'
我实现的字典是{'wmw2' : 55, 'abc3' : 90, 'jms45': 86})
def letter_grades(adict):
"""
Returns: a new dictionary with the letter grades for each student.
The dictionary adict has netids for keys and numbers 0-100 for values.
These represent the grades that the students got on the exam. This function
returns a new dictionary with netids for keys and letter grades (strings)
for values. Our cut-off is 90 for an A, 80 for a B, 70 for a C, 60 for a
D. Anything below 60 is an F.
Example: letter_grades({'wmw2' : 55, 'abc3' : 90, 'jms45': 86}) evaluates
to {'wmw2' : 'F, 'abc3' : 'A', 'jms45': 'B'}.
Parameter adict: the dictionary of grades
Precondition: alist is a list of ints
"""
# HINT: You will need a dictionary that acts as an accumulator
# Start with result = {}. Then add to this dictionary.
result = {}
for k in adict:
if result[k] >= 90:
result[k] = 'A'
elif result[k] >= 80:
result[k] = 'B'
elif result[k] >= 70:
result[k] = 'C'
elif result[k] >= 60:
result[k] = 'D'
else:
result[k] = 'F'
return result
你设定
所以,
result
是空的。 然后在结果上循环:for k in result:
。因此,循环只有零个元素要循环也许你想写
for k in adict:
然后,您永远不会给
result
赋值。在你的for loop
里写adict[k] = ...
。 也许你想写result[k] = ...
因此,这就产生了:
您希望根据
adict
dict创建result
dict。因此必须在adict
上创建条件,并在result
上进行赋值希望这能帮助你,问任何问题
相关问题 更多 >
编程相关推荐