Shrishail Talukar - 6 months ago 30

Python Question

`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

Function calls itself until the base case.

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

`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