I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have:
def average(n):
if n >= 0:
avg = sum((range(1:int(n)))/float(len(range(1:int(n)))))
print avg
how do I fix it?
I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have:
def average(n):
if n >= 0:
avg = sum((range(1:int(n)))/float(len(range(1:int(n)))))
print avg
how do I fix it?
If your range is always 1:n, why don't you just use this:
avg = sum((range(1:int(n)))/float(n))
Or maybe I am not understanding your question...
I may be wrong but range(1:int(n)) doesn't look like syntactically correct and parenthesis don't match. You may want to calculate the average of numbers in the range of 0 to n. In that case, I would replace your code like this:
def average(n):
if n >= 0:
avg = sum((range(int(n))))/float(n)
print avg
The summation of x from 1 to n is simply (n + 1) * (n / 2)
. The number of elements being summed is n
. Do a little simplification and your new function is
def average(n):
return (n + 1) / 2.0
You'll have to adjust this if you actually wanted Python's behavior of an exclusive upper-bound for range() (i.e., having average(10) return the average of the sum of values 1 - 9 instead of 1 - 10).