【问题标题】:Edhesive 7.5 code practice GPA average PythonEdhesive 7.5 代码练习 GPA 平均 Python
【发布时间】:2021-01-13 15:42:54
【问题描述】:

目前我的代码是:

def GPAcalc(grade, weighted):
   grade = grade.lower()
   dictionary = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}
   if weighted == 1 and grade in dictionary:
       return "Your GPA score is: "+str(dictionary[grade] + 1)
     
   elif weighted == 0 and grade in dictionary:
       return "Your GPA score is: "+str(dictionary[grade])
   else:
       return "Invalid"

def GPAav():
    grade = GPAcalc()
    for i in range(0,cl):
        grad= GPAcalc(grade,dictionary)
        total = grade + total
        print(total/cl)
cl = int(input("How many Classes are you taking? "))
for i in range(0,cl):
    print(GPAcalc(input("Enter your letter Grade: "), int(input("Is it weighted?(1= yes, 0= no) "))))
GPAav()

我必须从其余代码中找到十进制形式的平均 GPA 并将其输出。我将如何从 GPAcalc 中获取值并在 GPAav 中使用它,以便将其平均化?

【问题讨论】:

标签: python


【解决方案1】:

这里有 2 个选项。在输入成绩时将成绩存储在列表中或即时进行计算。我选择了第一个选项。如果您想在应用程序中添加功能,这允许您稍后使用数据。您可能还想将未加权成绩存储在元组列表中 ([('a',True),('b',False)...]),但我只存储加权成绩。

此外,如果您在阅读时验证用户输入的值是否正确,则可能会更容易。让他们不断重试,直到做对为止。

您的计算函数不应打印任何内容。他们应该只做他们需要做的计算并将结果作为数字返回。

grade_map = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0}

def GPAcalc(grade, weighted):
   # Data has already been sanitized, so no error checks needed
   return grade_map[grade] + weighted

def GPAav(grades):
    return sum(grades) / len(grades)

def input_grades():
    # TODO: Make sure user enters a number
    cl = int(input("How many classes are you taking? "))
    grades = []
    for _ in range(cl):
        # Loop until valid input
        while True:
            # Get input and convert to lower case
            grade = input("Enter your letter grade: ").lower()
            if grade in grade_map:
                # Ok data. Exit loop.
                break
            # This only prints on bad input
            print("Invalid input. Enter a,b,c,d or f. Try again...")
        # Loop until valid input
        while True:
            # Read the value as a string first to verify "0" or "1"
            weighted = input("Is it weighted?(1= yes, 0= no) ")
            if weighted in "01":
                # Verified. Now convert to int to avoid an exception
                weighted = int(weighted)
                break
            print("Invalid input. Enter 0 or 1. Try again...")
        # Store weighted numeric grade in list
        grades.append(GPAcalc(grade, weighted))
    return grades

grades = input_grades()
print(f"Your average GPA is {GPAav(grades)}.")

TODO:input_grades() 中的重复代码是一个危险信号,可能该代码可以移动到可重用的函数中。

【讨论】:

  • 我从中获取并将其与我自己的代码混合,但我不断收到此“TypeError: unsupported operand type(s) for +: 'int' and 'str' on line 15”指的是GPAav 函数
  • @ButterCCM 我必须查看代码。我的答案中的代码没有给出任何错误:repl.it/@JohnnyMopp/CarpalWrithingSquare#main.py
  • 呃,奇怪,一定是我用来编译学校的东西
猜你喜欢
  • 1970-01-01
  • 2021-05-17
  • 2023-03-10
  • 2016-05-27
  • 2017-01-11
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多