代码显示赋值前引用的变量



我从代码"UnboundLocalError:赋值前引用的局部变量'lower'"中得到这个错误。为什么我会得到这个?在这种情况下,"分配前引用"的真正含义是什么?因为我认为只有在定义了"分数"变量之后,我才会将变量指定为"最低"。如有任何帮助,我们将不胜感激。

def main():
        scores = get_score()
        total = get_total(scores)
        lowest -= min(scores)
        average = total / (len(scores) - 1)
        print('The average, with the lowest score dropped is:', average)

def get_score():
        test_scores = []
        again = 'y'
        while again == 'y':
                    value = float(input('Enter a test score: '))
                    test_scores.append(value)
                    print('Do you want to add another score? ')
                    again = input('y = yes, anything else = no: ')
                    print()
        return test_scores
def get_total(value_list):
        total = 0.0
        for num in value_list:
                    total += num
        return total

main()

您使用的是-=,它需要一个起始值。但你没有提供一个起始值。在上下文中,您似乎打算使用=。

这是因为在main()中你说的是

lowest -= min(scores)

其基本上是最低的=最低-分钟(分数)。由于您之前没有最低设置,您将得到错误

您的最低变量没有定义。您使用"最低-=最低(分数)",这意味着从最低值中减去最低值,但最低值还不存在。根据变量的名称,我猜你想做的是:

def main():
    scores = get_score()
    total = get_total(scores)
    lowest = min(scores)
    average = total / (len(scores) - 1)
    print('The average, with the lowest score dropped is:', average)

最新更新