Bobby
Bobby

Reputation: 21

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)

Upvotes: 2

Views: 5031

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56684

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!"

Upvotes: 1

Philipp
Philipp

Reputation: 49852

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)

Upvotes: 3

Related Questions