用于循环加法器的问题

2024-07-02 12:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建下面参数描述的函数,但我一直得到以下输出值,不知道为什么

输出错误消息:

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

Tags: theinanfordictionaryiswithresult
1条回答
网友
1楼 · 发布于 2024-07-02 12:49:28

你设定

`result = {}`

所以,result是空的。 然后在结果上循环:for k in result:。因此,循环只有零个元素要循环
也许你想写for k in adict:

然后,您永远不会给result赋值。在你的for loop里写adict[k] = ...。 也许你想写result[k] = ...

因此,这就产生了:

result = {}
for k in adict:
    if adict[k] >= 90:
        result[k] = 'A'
    elif adict[k] >= 80:
        result[k] = 'B'
    elif adict[k] >= 70:
        result[k] = 'C'
    elif adict[k] >= 60:
        result[k] = 'D'
    else:
        result[k] = 'F'
return result

您希望根据adictdict创建resultdict。因此必须在adict上创建条件,并在result上进行赋值

希望这能帮助你,问任何问题

相关问题 更多 >