【问题标题】:Python Create a program that performs and analysis on final grades in a coursePython 创建一个程序来执行和分析课程中的最终成绩
【发布时间】:2017-09-02 00:03:14
【问题描述】:

以下是我应该做的 创建一个程序来执行和分析课程中的最终成绩。程序必须使用循环并将每个等级添加到列表中。该程序要求用户输入 10 名学生的最终成绩(整数百分比)。然后程序将显示以下数据:

  • 全班最高分。
  • 全班最低分。
  • 班级的平均分。

我在第 12 行不断收到错误消息,无法弄清楚原因。

错误:

Traceback (most recent call last):
  File "H:/COMS-170/program7.py", line 33, in <module>
    main()

  File "H:/COMS-170/program7.py", line 12, in main
    total = sum(info)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

代码:

def main():
    info = get_values()
    total = sum(info)
    average = total/len(info) 
    print('Highest Grade: ', max(info))
    print('Lowest Grade: ', min(info))  
    print('Average is: ', average)

def get_values():
    num_grades = 10
    #making of the list
    grades = []
   #ask the user for the info
   print('Please enter the final grades for 10 students: ')

   #put the info into the list with a loop 
   for i in range(num_grades):
   grade = input('Enter a grade: ')
   grades.append(grade)
  return grades
main()

【问题讨论】:

  • 您遇到了什么错误。这是“意外缩进”错误吗?第 12 行之后的所有内容似乎都使用 3 个空格而不是 4 个空格。
  • @TehTris 不,它是一个 Traceback(最近一次调用最后一次):文件“H:/COMS-170/program7.py”,第 33 行,在 main() 文件“H: /COMS-170/program7.py",第 12 行,总和 = sum(info) TypeError: unsupported operand type(s) for +: 'int' and 'str'

标签: python list append average min


【解决方案1】:

您的解决方案需要稍作修正,因为您的用户输入返回 str 值并且您想要 sum 那些,但首先将它们转换为 ints,如下所示:

def main():
    info = get_values()
    total = sum(info)
    average = total/len(info) 
    print('Highest Grade: ', max(info))
    print('Lowest Grade: ', min(info))  
    print('Average is: ', average)

def get_values():
    num_grades = 10
    #making of the list
    grades = []
    #ask the user for the info
    print('Please enter the final grades for 10 students: ')

    #put the info into the list with a loop 
    for i in range(num_grades):
        grade = int(input('Enter a grade: ')) # convert the input `str` to `int`
        grades.append(grade)
    return grades
main()

您还应注意在int 转换期间不会发生异常,例如ValueError

希望对你有帮助!

【讨论】:

    【解决方案2】:

    问题是,在你从输入中读取之后,你会在 Grades 变量中得到一个字符串列表。 因此,您可以使用 int 方法来解析输入:

    grades.append(int(grade))
    

    【讨论】:

    • 不客气。如果需要处理浮点数,原理是一样的
    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多