0

I hope this is not too much of a stupid question, but why does the 'return 1' statement in this Python code return the factorial of a number? This also happens for 'return True', which I understand is equivalent to 'return 1'

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
1
  • return 1 does not return the factorial of a number all by itself; it depends on all the other values that have already been calculated in the recursion chain. Commented Jul 10, 2020 at 1:37

2 Answers 2

1

n == 0 is the base case of the recursive function. Factorial of 0 is 1: reference

Once the base case returns 1, the statement return n * factorial(n-1) will have the form: return n * 1 and so on.

Sign up to request clarification or add additional context in comments.

Comments

0

in python when you multiply a number by True it will operate like you are multiply by One, and when you multiply a number by False it will operate like when you multiply by Zero.

so this is why you get a factorial af a number even if you use:

return True

instead of

return 1

but if you will call factorial(0) you will get True instead of 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.