y=0
n= int(input("gff"))
def geometricsum(n):
global y
while n>0:
y=y+1/n**2
geometricsum(n-1)
print(geometricsum(n))
I’ve tried to print geometric sum which take n as the input to find the geometric sum of n numbers.
In which the function does. If n is 2 the function calculates 1/1**2 + 1/2**2 ...
.
You appear to have most of the parts and pieces but you’re not necessarily applying them in the correct order. Two pieces you’re missing are an explicit return
statement and a tighter limit on the range of numbers this function can accept:
def geometricsum(n):
if n < 1:
raise ValueError('domain error')
y = 1 / n**2
if n > 1:
y += geometricsum(n - 1)
return y
natural_number = int(input("gff: "))
print(geometricsum(natural_number))
while n>0
– Nothing in this loop ever modifiesn
, so by what logic would this loop ever end?I think you meant to use
if
, notwhile
. But there are probably other mistakes as well.Even using
if
,geometricsum
neverreturn
s anything.It’s usually a bad idea to use global variables in a recursive function. Make
y
a parameter and return it.“If so how”: this is a question you can answer yourself. Use a debugger, set breakpoints and step through the code inspecting variables.
Show 1 more comment