0

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
Stephen-Njoroge
  • 145
  • 2
  • 10

2 Answers2

1

To get the average you want this:

average = float(total)/n

Some examples:

>>> float(101/2)
50.0
>>> 101/2
50
>>> float(101)/2
50.5
Nick Bull
  • 9,518
  • 6
  • 36
  • 58
  • Thanks a lot, I was wondering where the problem was. – Stephen-Njoroge Aug 07 '16 at 12:59
  • 1
    FWIW, `1.0 * a / b ` is better than `float(a) / b`. It's faster, since it avoids a function call, and it's more general (it handles complex numbers properly). But really, it's better to use `from __future__ import division` unless you're using a really ancient version of Python that doesn't support that import. – PM 2Ring Aug 07 '16 at 13:07
  • @PM2Ring I've never written anything much in Python to know, but I'll remember that! Thanks for your input. – Nick Bull Aug 07 '16 at 13:13
  • @PM2Ring Wow true that is really effective thinking. – Stephen-Njoroge Aug 07 '16 at 13:21
1

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.

Israel Unterman
  • 13,158
  • 4
  • 28
  • 35