I'm making a Python exercise for my university homework and I can't seem to figure it out. I need to make the sum of 1/n^2, n being a value introduced by the user.
Example:
user puts n=4
Program Calculates: 1+1/4+1/9+1/16= 1.42361111
This is what I have so far:
num = int(input("n: "))
sum = 0
x=1
while x<=num:
sum=1/(x*x)
x=x+1
print ("the sum is:" , sum)
Taking all of the good advice in the comments into an answer:
sum as a variable as that's already a function name in Python.sum to itself each iteration, otherwise sum is just overwritten each iteration.x*x which is the same as x**2. So this is a totally moot point.) I believe your denominator should be x**2 not x**x based on your first paragraph.num = int(input("n: "))
output_sum = 0
x = 1
while x <= num:
output_sum += 1/(x**2)
x += 1
print ("the sum is:" , output_sum)
>>the sum is: 1.4236111111111112
Note: I switched from x = x+1 to the more common form x += 1. The same addition using the +=operator is being used for your output_sum as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With