[英]Averaging inputs from user
第四个作业涉及编写一个 Python 程序来计算一组五名学生的平均测验成绩。 你的程序应该包括一个包含五个名字的列表。 使用 for 循环,它应该连续提示用户输入五个学生中每个学生的测验成绩。 每个提示都应包括要输入测验成绩的学生的姓名。 它应该计算并显示这五个等级和最高等级的平均值。 你应该决定这五个学生的名字。
所以这是我的任务,下面是我到目前为止的任务。
# This program will compute the average quiz grade for 5 students
print ("Hello, this program is designed to compute the average quiz grades for the following students: Clark, Nicole, Kiran, Alex, and Erik")
students = ["Clark", "Nicole", "Kiran", "Alex", "Erik"]
for student in students:
print (student, ", What was your quiz grade?")
grades = eval(input("My grade is: "))
该计划会询问每个学生的成绩。 但是,我需要取这些数字并以某种方式将它们相加,这样我就可以在之后将它们除以求平均值。 任何人都可以建议我解决这个问题的正确途径吗?
是的。 首先,我已经为您修复并格式化了您的代码。
# This program will compute the average quiz grade for 5 students
print("Hello, this program is designed to compute the average quiz grades for the following students: Clark, Nicole, Kiran, Alex, and Erik")
students = ["Clark", "Nicole", "Kiran", "Alex", "Erik"]
for student in students:
print(student, ", What was your quiz grade?")
grades = input("My grade is: ")
到目前为止,您可以向每个学生询问成绩。 一旦他们告诉您,您应该将其存储在内存中。 一个简单的方法是使用列表(我假设你还没有学习字典)。
您可以在询问成绩之前创建一个新列表,然后将用户输入的每个新成绩添加到列表末尾。
# This program will compute the average quiz grade for 5 students
print("Hello, this program is designed to compute the average quiz grades for the following students: Clark, Nicole, Kiran, Alex, and Erik")
students = ["Clark", "Nicole", "Kiran", "Alex", "Erik"]
grades = [] # create an empty list to store the grades in
for student in students:
print(student, ", What was your quiz grade?")
grade = input("My grade is: ")
grades.append(int(grade)) # convert the grade to an integer number, then add it to the list
print("Here are the grades you entered: ", grades)
现在,我们需要计算列表的平均值。 回顾初等数学,一组数字的平均值是这些数字的总和除以数字的数量。
在 Python 中,您可以使用内置函数sum()
来计算数字的总和。 您可以使用内置函数len()
来获取列表中的元素数量。
现在,您只需将总和除以长度即可。
average = sum(grades) / len(grades)
print("The average is:", average)
现在,为了获得最高等级,您可以使用内置函数max()
。 这将找到并返回数组中最大的数字。
你可以像这样使用它。
highest = max(grades)
print("The highest grade is:", highest)
如果您想要组合代码:
# This program will compute the average quiz grade for 5 students
print("Hello, this program is designed to compute the average quiz grades for the following students: Clark, Nicole, Kiran, Alex, and Erik")
students = ["Clark", "Nicole", "Kiran", "Alex", "Erik"]
grades = [] # create an empty list to store the grades in
for student in students:
print(student, ", What was your quiz grade?")
grade = input("My grade is: ")
grades.append(int(grade)) # convert the grade to an integer number, then add it to the list
print("Here are the grades you entered: ", grades)
average = sum(grades) / len(grades)
print("The average is:", average)
highest = max(grades)
print("The highest grade is:", highest)
有没有办法在不存储它们的情况下运行此代码并计算结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.