Reputation: 1
I'm asked to write a function that should return the sum of the following series 1000 + 1/1**2 + 1/2**2 + 1/3**2 + 1/4**2 + ... + 1/n**2
for the given integer n.
For example, for n = 0, the function should return 1000, for n = 1,
the function should return 1001, for n = 2, the function should return 1001.25, for n = 3, the function should return 1001.3611111111111, etc.
I know for sure this needs to be done by for loops and range functions. Here's my code
if n<0:
return None
if n>0 or n==0:
for i in range(1,n-1):
result=1000+1/(i**2)
return result
But it keeps return None when n=o,1,2,3 I'm not sure how to fix this code...
Upvotes: 0
Views: 660
Reputation: 13939
In each iteration, you are not updating result
using the previous value of it. (Also you are returning result
prematurely.) Update the variable by using result = result + 1 / (i ** 2)
, or equivalently, result += 1 / (i ** 2)
.
def foo(n):
result = 1000
for i in range(1, n+1):
result += 1 / (i ** 2)
return result
print(foo(0), foo(1), foo(2), foo(3)) # 1000 1001.0 1001.25 1001.3611111111111
Or, using (generator) comprehension,
def foo(n):
return 1000 + sum(1 / (i ** 2) for i in range(1, n + 1))
Upvotes: 2
Reputation: 56
First, you can only return from within a function, but your code has no function definition included - maybe you forgot. Second, if this code is part of a function, the first iteration of the loop will throw you out of the function as soon as it hits return, so this function, if implemented, will not complete the intended loop iterations. Since this is a homework question, I will not complete the code, but I hope this gives you a start.
Upvotes: 0
Reputation: 230
You don't need any if statements. What you're doing right now is calculating result
, then immediately returning the result on step 1.
result = 1000
for i in range(1,n+1):
result += 1/(i**2)
return result
Comment if anything doesn't make sense
Upvotes: 0