steve254 - 7 months ago 24

Python Question

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)

sum_and_average(100)

It returns:

`the sum is 5050 and the average is 50.000000`

Answer

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 `float`

ing the result is already too late.