我正在开展一项小型练习计划,让您可以为您喜欢的学生输入3个考试成绩,最后我希望计算所有学生之间的平均成绩。我可以输入所有学生的姓名和分数,它会让我回到他们的平均水平,但当你进入" *"它只计算最后一个学生的平均值,我试图弄清楚如何根据他们的考试成绩计算所有学生的平均分数
def GetPosInt():
nameone = str
while nameone != "*":
nameone =(input("Please enter a student name or '*' to finish: "))
if nameone != "*":
scoreone = int(input("Please enter a score for " + nameone +": "))
if scoreone < 0:
print("positive integers please!")
break
else:
scoretwo = float(input("Please enter another score for "+nameone+": "))
scorethree = float(input("Please enter another score for "+nameone+": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3
print("The average score for",nameone,"is ",avg)
classtotal = avg
if nameone == "*":
classavg = classtotal / 3
print("The class average is: ",classavg)
# main
def main():
GetPosInt()
main()
答案 0 :(得分:1)
以下是代码的简化版本,它使用列表为多个学生存储数据,然后在最后显示这些详细信息,并计算班级平均值(注释内容)。
def GetPosInt():
names = [] # declare the lists you'll use to store data later on
avgs = []
while True:
name = ...
if name != "*":
score1 = ...
score2 = ...
score3 = ...
avg = (score1 + score2 + score3) / 3 # calculate the student average
# append student details in the list
names.append(name)
avgs.append(avg)
else:
break
for name, avg in zip(names, avgs): # print student-wise average
print(name, avg)
class_avg = sum(avg) / len(avg) # class average
答案 1 :(得分:0)
COLDSPEED在我处理问题时为您提供了问题解决方案。如果你想看到不同的解决方案。就在这里......你可以为分数设定条件。
def GetPosInt():
numberOfStudents = 0.0
classtotal = 0.0
classavg = 0.0
while(True):
nam = (raw_input("Please enter a student name or '*' to finish "))
if(nam == '*'):
print("The average of the class is " + str(classavg))
break
numberOfStudents += 1.0
scoreone = float(input("Please enter the first score for " + str(nam) + ": "))
scoretwo = float(input("Please enter the second score for " + str(nam) + ": "))
scorethree = float(input("Please enter the third score for " + str(nam) + ": "))
testscores = scoreone + scoretwo + scorethree
avg = testscores / 3.0
print("The average score for " + str(nam) + " is " + str(avg))
classtotal += avg
classavg = classtotal / numberOfStudents
def main():
GetPosInt()
main()