【问题标题】:Dividing a string by an integer to get GPA calculation将字符串除以整数以获得 GPA 计算
【发布时间】:2022-01-01 04:51:12
【问题描述】:

我正在使用 Python 并正在编写一个程序,用户可以在其中输入他们想要计算的课程数量。然后程序应该获取附加的项目(字符串),然后将它们除以他们想要的课程数量,换句话说,总数(整数)。我似乎无法找到正确实施此功能的方法,有什么帮助吗?问题在于 If value = 1。

if (value == 1):
    selection = int(input("How many classses would you like to include?\n"))
    for i in range (0,selection):
        print("What is the grade of the class?")
        item = (input())
        grades.append(item)
        GPA_list = [sum(item)/selection for i in grades]
        print(GPA_list)
    

【问题讨论】:

  • 用户输入的是什么类型的字符串?字母等级?数字分数?您不能将字母 D 除以数字。
  • item 可能应该是float,而不是str
  • 为什么不将项目转换为浮点数?
  • 是的,你在item 上运行sum,但itemm 是一个字符串。此外,一旦您将所有项目附加到列表中,您可能应该在 for 循环之外构建列表。
  • 用户应该输入数字分数,我将如何将项目从字符串转换为浮点数,我尝试了浮点数(输入()),但它说浮点数对象不可交互

标签: python gpa


【解决方案1】:

您可以使用mean 来简化这个过程,它会为您进行求和和除法:

>>> from statistics import mean
>>> print(mean(
...     float(input(
...         "What is the grade of the class?\n"
...     )) for _ in range(int(input(
...         "How many classes would you like to include?\n"
...     )))
... ))
How many classes would you like to include?
5
What is the grade of the class?
4
What is the grade of the class?
3
What is the grade of the class?
4
What is the grade of the class?
2
What is the grade of the class?
4
3.4

要修复现有代码,您需要做的就是确保将 item 转换为浮点数,然后在 grades 而不是每个 item 上调用 sum

grades = []
selection = int(input("How many classses would you like to include?\n"))
for i in range(0, selection):
    print("What is the grade of the class?")
    item = float(input())
    grades.append(item)
    GPA_list = sum(grades) / selection
    print(GPA_list)

请注意,您的代码会在循环中的每个步骤打印平均值的一小部分,直到最终在最后一次迭代中打印出正确的结果;如果您也想解决此问题,请取消缩进最后两行。

【讨论】:

  • 非常感谢!你真的帮了我,它成功了!我会支持你,但它不会让我哈哈。
  • @jfcrespo 但是,您可以通过单击复选标记来接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
  • 2016-07-03
  • 1970-01-01
  • 2015-11-02
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多