GPA计算器,如何将列表中的值添加到变量?

时间:2019-01-17 04:03:01

标签: python python-3.x

我试图将GPA计算器创建为一个小项目,但是我无法弄清楚如何将用户输入的值加在一起。我正在使用if和elif命令为每个字母等级指定一个GPA数字。但是,当我尝试将所有变量加到变量“ gtotal”的末尾时,它总是说0。我不知道即时通讯出现了问题,非常感谢您的帮助。

            print ("GPA Calculator")

            gtotal = 0
            ctotal = 0

            grades = []
            for i in (range(6)):
                grades.append(input("Enter Grades in Order Here: "))
                if grades == "A":
                    gtotal += 4
                elif grades == "A-":
                    gtotal += 3.7
                elif grades == "B+":
                    gtotal += 3.3
                elif grades == "B":
                    gtotal += 3
                elif grades == "B-":
                    gtotal += 2.7
                elif grades == "C+":
                    gtotal += 2.3
                elif grades == "C":
                    gtotal += 2
                elif grades == "C-":
                    gtotal += 1.7

            print(gtotal)

我希望看到一个汇总了代表用户字母输入的所有整数的总和。但是当我打印(gtotal)时它始终返回0

2 个答案:

答案 0 :(得分:3)

与其创建if else循环,不如使用字典。在这里,我将与字母等级相对应的等级相加,然后将其除以主题数。结果,您将获得加权平均绩点。

In [3]: def get_grade(grade_list):
            grade_dict = dict(zip(['A', 'A-', 'B+', 'B-', 'C+', 'C-'],
                                  [4, 3.7, 3.3, 3, 2.7, 2.3, 2, 1.7]))
            return sum([grade_dict[i] for i in grade_list])/(len(grade_list))

In [4]: get_grade(['A', 'A', 'A', 'B+'])
Out[4]: 3.825

答案 1 :(得分:1)

您正在尝试附加grades,因此在6次迭代之后,它将是6个值的列表。由于您为每次迭代都添加了gtotal,因此当您删除append函数时,代码将起作用。

代码:

print ("GPA Calculator")

gtotal = 0
ctotal = 0

grades = []
for i in (range(6)):
    grades = input("Enter Grades in Order Here: ")
    if grades == "A":
        gtotal += 4
    elif grades == "A-":
        gtotal += 3.7
    elif grades == "B+":
        gtotal += 3.3
    elif grades == "B":
        gtotal += 3
    elif grades == "B-":
        gtotal += 2.7
    elif grades == "C+":
        gtotal += 2.3
    elif grades == "C":
        gtotal += 2
    elif grades == "C-":
        gtotal += 1.7

print(gtotal)

输出:

GPA Calculator
24
Enter Grades in Order Here: A
Enter Grades in Order Here: A
Enter Grades in Order Here: A
Enter Grades in Order Here: A
Enter Grades in Order Here: A
Enter Grades in Order Here: A