简体   繁体   中英

How do I get the sum of all numbers in a range function in Python?

I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but I can't seem to get it right!

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)

Your code doesn't add anything, it just overwrites x in each iteration. Adding something to a variable can be done with the += operator. Also, don't use 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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM