我不知道如何把x(从下面的代码中)加到它自身,得到和,然后除以评级的数量。课堂上给出的例子是4个等级,数字是3、4、1和2。平均评分应该是2.5分,但我似乎做得不对!
number_of_ratings = eval(input("Enter the number of difficulty ratings as a positive integer: ")) # Get number of difficulty ratings
for i in range(number_of_ratings): # For each diffuculty rating
x = eval(input("Enter the difficulty rating as a positive integer: ")) # Get next difficulty rating
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
最佳答案
您的代码没有添加任何内容,只是在每次迭代中覆盖x
。可以使用+=
运算符向变量添加内容。另外,不要使用eval
:
number_of_ratings = int(input("Enter the number of difficulty ratings as a positive integer: "))
x = 0
for i in range(number_of_ratings):
x += int(input("Enter the difficulty rating as a positive integer: "))
average = x/number_of_ratings
print("The average diffuculty rating is: ", average)
关于python - 如何获取Python范围函数中所有数字的总和?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4964286/