steve254 steve254 - 2 months ago 6x
Python Question

Python finding n as 101 instead of 100

Python loops are finding n as 101 instead of 100, I am getting the average of 5050 as 50 instead of 50.50, What could be the problem? How should I go through it? Here is my function.

def sum_and_average(n):
total = 0
for i in range(1, n+1):
total += i
average = float(total/n)
print "the sum is %d and the average is %f" %(total, average)


It returns:

the sum is 5050 and the average is 50.000000


Do float(total) / n.

In Python 2 when one of the arguments is float, the calculation will be carried out in float.

But doing float(total/n) won't work, since total/n has already been calculated in integers, and floating the result is already too late.