平均for循环中变量的不同迭代

时间:2016-03-22 00:47:30

标签: python loops for-loop average

我似乎无法解决这个问题 - 我希望得到该程序结束时所有输入的平均值,但我不知道如何在循环的每次迭代中保存输入。非常感谢任何帮助,谢谢!

students = int(input("How many students are in your class?"))

while students <= 0:
    print ("Invalid # of students. Try again.")
    students = int(input("How many students are in your class?"))

studentnum = 1 

for x in range (0, students):
    print ("*** Student", studentnum, " ***")
    score1 = int(input("Enter score for test #1"))
    while score1 < 0:
            print ("Invalid score. Try again.")
            score1 = int(input("Enter score for test #1"))
    score2 = int(input("Enter score for test #2"))
    while score1 < 0:
            print ("Invalid score. Try again.")
            score1 = int(input("Enter score for test #1"))
    part1 = score1 + score2
    av = part1 / 2
    print ("Average score for student #", studentnum, "is", av)
    studentnum = studentnum + 1

# figure out how to average out all student inputs

2 个答案:

答案 0 :(得分:2)

只需创建一些东西将它们存储在循环外部

scores = []
for x in range (0, students):
   ...
   scores.append({'score1': score1, 'score2': score2, 'avg', av})

total_avg = sum(d['avg'] for d in scores) / len(scores)

答案 1 :(得分:1)

您可以为每个学生建立一个平均分数列表(通过在每个循环迭代中附加它),然后在退出循环后找到它们的平均值:

student_average_scores = []

for student in xrange(students):
    # <your code that gets av>
    student_average_scores.append(av)

average_score = sum(student_average_scores) / float(len(student_average_scores))