append是添加总和,而不是添加到列表中

flvtvl50  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(352)

我试图添加,但每当我试图在 main() ,它将打印平均值,但将其相加。

def letter_grade(test_score):
    if int(test_score) >= 90:
        grade = 'A'
    elif int(test_score) >= 80:
        grade = 'B'
    elif int(test_score) >= 70:
        grade = 'C'
    elif int(test_score) >= 60:
        grade = 'D'
    else:
        grade = 'F'
    return grade

def calc_avg_grade(test_score):
    average = []
    func_sum = sum(test_score)
    avg = func_sum/5.00
    average.append(avg)
    average.reverse()
    return average

def main():
    grades = []
    i = 0
    outfile = open('studentgrades.txt', 'w')
    while i < 4:
        name = input("Enter the student name: ")
        for x in range(5):
            score = float(input("Enter number grade: "))
            grades.append(score)
            gradle = letter_grade(score)
            print(str(score) + ' - ' + gradle)
        avg_grade = calc_avg_grade(grades)
        avgg = avg_grade
        print(name + "'s average grade is: " + str(avgg))
        outfile.write(name + ', ' + str(avg_grade) + "\n")
    txtcontents = outfile.read()
    print(txtcontents)

if __name__ == "__main__":
    main()

它运行append的部分是我遇到的问题: print(name + "'s average grade is: " + str(avgg)) 这是def main()。

ecbunoof

ecbunoof1#

我认为您没有重新初始化 grades :

def main():
    # grades = []  # Not Here!
    i = 0
    outfile = open('studentgrades.txt', 'w')
    while i < 4:
        name = input("Enter the student name: ")
        grades = []  # here instead
        for x in range(5):
            score = float(input("Enter number grade: "))
            grades.append(score)
            gradle = letter_grade(score)
            print(str(score) + ' - ' + gradle)
        avg_grade = calc_avg_grade(grades)
        avgg = avg_grade
        print(name + "'s average grade is: " + str(avgg))
        outfile.write(name + ', ' + str(avg_grade) + "\n")
    txtcontents = outfile.read()
    print(txtcontents)

这样你会得到一个新的空的 grades 每名学生及 avg_grade 将是该学生的正确平均值。

相关问题