Home > Net >  why my Python recursive function not working?
why my Python recursive function not working?

Time:08-25

Hey everyone hope you all doing great! I was practicing my python, I write a code to execute the factorials of the given Number but the code didn't execute!

The code

def factorial_recursive(n):
    if n == 1 or n == 0:
        return 1
        return n * factorial_recursive(n-1)

f = factorial_recursive(5)
print(f)

After running Python File: None

where the answer must be 120 as factorial of 5 is 120

CodePudding user response:

You have your second return statement indented in the if statement. The second return should be for any other cases. Here is the correct function:

def factorial_recursive(n):
    if n == 1 or n == 0: 
        return 1
    return n * factorial_recursive(n-1)

f = factorial_recursive(5)
print(f)

Outputs: 120

CodePudding user response:

You need to call the function like so:

f=factorial_recursive(4)
print(f)

If you actually want to use it on some number (like 4).

Also, you should learn to format your code on stack overflow. Makes it easy for others to understand your code.

  • Related