Why is this recursive function showing stuck cursor. Is it caused by infinite loops. If so how? [closed]

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 ....

  • 5

    while n>0 – Nothing in this loop ever modifies n, so by what logic would this loop ever end?

    – 

  • 1

    I think you meant to use if, not while. But there are probably other mistakes as well.

    – 




  • 1

    Even using if, geometricsum never returns anything.

    – 

  • 2

    It’s usually a bad idea to use global variables in a recursive function. Make y a parameter and return it.

    – 

  • 1

    “If so how”: this is a question you can answer yourself. Use a debugger, set breakpoints and step through the code inspecting variables.

    – 

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))

Leave a Comment