我正在执行此代码并且我收到一个 UnboundLocalError: local variable 'points' referenced before assignment

时间:2021-04-14 13:23:09

标签: python python-3.x python-2.7

我有我的作业代码。不幸的是,我收到一个未绑定的本地错误 - :

UnboundLocalError: local variable 'points' referenced before assignment. 

你能帮我解决这个问题,让我能够理解吗?

def do_calc(x, y):
    grade_1 = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
    points = 0
    count = 0
    while count < y:
        for i in range(y):
            letterGrade = raw_input("Enter letter grade: ")
            points += grade_1[letterGrade.lower()]
            count +=1   
        return x, y

def main():
    x, y = do_calc(x, y)
    Grade_point_average = x/y
main()

2 个答案:

答案 0 :(得分:1)

我认为您认为 points 必须传递给 do_calculation,而实际上它只是返回:

def do_calculation(number):
    grades = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
    points = 0
    count = 0
    while count < number:
        for i in range(number):
            letterGrade = input("Enter letter grade: ")
            points += grades[letterGrade.lower()]
            count +=1
            print(points)    
        return points

def main():
    name = input("Enter your name:")
    grade_title = input("Enter your grade      level[Ex.Freshman,Sophmore,Junior,Senior]:")
    number = int(input("Enter number of courses: "))
    points = do_calculation(number)
    GPA = points/number
    print("Grade level:", grade_title)
    print("Hello", name, "Your GPA is", GPA)
main()

实际上,number 参数应该传入而返回。

所以你的函数接受 number 并返回 points

答案 1 :(得分:1)

您似乎不需要将“点”传递给 do_calculation。 (此外,您的缩进在方法末尾看起来可能不正确。)

def do_calculation(number):
    grades = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
    points = 0
    count = 0
    while count < number:
        for i in range(number):
            letterGrade = input("Enter letter grade: ")
            points += grades[letterGrade.lower()]
            count +=1
    print(points)    
    return points