在Python中如何获得范围函数中所有数字的和?

2024-10-01 15:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何取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)

Tags: ofthenumberinputgetasevalinteger
2条回答

您的代码不添加任何内容,它只是在每次迭代中重写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)
try:
    inp = raw_input
except NameError:
    inp = input

_sum = 0.0
_num = 0
while True:
    val = float(inp("Enter difficulty rating (-1 to exit): "))
    if val==-1.0:
        break
    else:
        _sum += val
        _num += 1

if _num:
    print "The average is {0:0.3f}".format(_sum/_num)
else:
    print "No values, no average possible!"

相关问题 更多 >

    热门问题