我的 For 循环返回错误的预期结果

时间:2021-07-06 22:32:58

标签: python loops for-loop math

我的代码:

#Program to calculate statistics from student test scores.
midterm_scores = [99.5, 78.25, 76, 58.5, 100, 87.5, 91, 68, 100]
final_scores = [55, 62, 100, 98.75, 80, 76.5, 85.25]

#Combine the scores into a single list
all_scores = midterm_scores + final_scores

num_midterm_scores = len(midterm_scores)
num_final_scores = len(final_scores)

print(num_midterm_scores, 'students took the midterm.')
print(num_final_scores, 'students took the final.')

#Calculate the number of students that took the midterm but not the final
dropped_students = num_midterm_scores - num_final_scores
print(dropped_students, 'students must have dropped the class.')

lowest_final = min(final_scores)
highest_final = max(final_scores)

print('\nFinal scores ranged from', lowest_final, 'to', highest_final)

# Calculate the average midterm and final scores
# Hint: Sum the midterm scores and divide by number of midterm takers
#       Repeat for the final
average_midterm = 0
for i in range(len(midterm_scores)):
    average_midterm += average_midterm + i

average_midterm = average_midterm / len(midterm_scores)
print('The average midterm score for the class is:', average_midterm)

average_final = 0
for x in range(len(final_scores)):
    average_final += average_final + x
    
average_final = average_final / len(final_scores)
print('The average final score for this class is:', average_final)

除非我的数学真的这么差,否则为什么我的平均考试成绩完全错误?是我的 For 循环或参数错误还是我的数学错误?

请原谅我的新手问题,谢谢。

1 个答案:

答案 0 :(得分:0)

您应该尝试改用 Python 的内置 sum 函数。

average_midterm = sum(midterm_scores) / len(midterm_scores)
相关问题