Python创建了一个程序来执行和分析课程的最终成绩

2024-06-26 13:48:10 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我想做的 创建一个程序,对课程的最终成绩进行分析。程序必须使用循环,并在添加每个等级时将其附加到列表中。程序要求用户输入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'

代码:

^{pr2}$

Tags: 用户inpy程序列表main错误line
2条回答

当用户输入返回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。在

希望有帮助!在

问题是,从输入中读取后,您将得到grades变量中的字符串列表。 因此,可以使用int方法解析输入:

grades.append(int(grade))

相关问题 更多 >