Shrishail Talukar Shrishail Talukar - 1 month ago 7
Python Question

Recursion: Why does function returns factorial of a number instead of returning 1?

def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)


def rec():
print fact(5)

rec()


[A question from newbie]

Python script.

This question remained in mind for a long time, let me explain my understanding so far on recursion.

In rec() function I called one more function fact(5), now the process is went to fact(n) function.

Function calls itself until the base case.

In else part:

5 * fact( 4 )

5 * 4 * fact( 3 )

5 * 4 * 3 * fact( 2 )

5 * 4 * 3 * 2 * fact( 1 )

Now the value of n becomes 0, and return 1

My question is, why the fact(n) function returns 120 instead of 1.

def check(x):
if x == 1:
return 10
else:
return 20

print check(1) // Prints 10
print check(3) // Prints 20


I hope you understood my question.

Thank you.

Answer

You itself answering the question

In else part:

5 * fact( 4 )

5 * 4 * fact( 3 )

5 * 4 * 3 * fact( 2 )

5 * 4 * 3 * 2 * fact( 1 )

then

5 * 4 * 3 * 2 * 1 * fact( 0 )

after that it goes in the if part that is returning 1

if n == 0:
        return 1

So expression is like this

5 * 4 * 3 * 2 * 1 * 1

=120

Comments