Home > Software engineering >  Why is this recursion python code print y and cant return y?
Why is this recursion python code print y and cant return y?

Time:06-04

So I have tried to create a recursion function which returns factorial of a number. I cant make it return y but I dont know why, can someone explain?

y = 1
def factorial(x):
    global y
    if x <= 1:
        print(y)
        return y
    else:
        y = y * x
        factorial(x-1)

def hey(): #random funtion which can return y but factorial cant.
    return y
print(factorial(3))
print(hey())


result in terminal:
6 #factorial can print y
None# Cant return y
6 # Other function can return y

CodePudding user response:

You need to propagate the return:

def factorial(x):
    global y
    if x <= 1:
        print(y)
        return y
    else:
        y = y * x
        return factorial(x-1)

Also, there's no need to use a global variable, a simpler solution:

def factorial_recursive(x):
    if x <= 1:
        return 1
    else:
        return x * factorial_recursive(x-1)

CodePudding user response:

you forgot the return before the recursion, and also why are you using a global variable ??, here's a simpler version without your y:

def factorial(x):
    if x <= 1:
        return 1
    else:
        return x * factorial(x-1)

print(factorial(3))

output:

6

CodePudding user response:

Thank you guys, I forgot to propagate the return. I was accually using a global variable just to make things more interesting, testing, and it worked. Now I understand the code.

  • Related