I am not getting this factorial function? I have managed to write the code through the hint available itself in the exercise.

But how this code works?

def factorial(x): (Defining a function)
if x == 1: (If the value is equals to one it should return the 1)
return 1
return x * factorial(x -1) (Not getting how this part works)(How it will check and multiply the number)(How it will convert as a loop because we are under if statement?)
(How it will work eg: factorial(4) will work 4*(4-1)!)
(Also not getting if there is an factorial function or not in the python because when running the factorial in python then it replies as factorial in not defined)


Before we get to the code, are we clear on factorial? Please explain the expected outcome. Thank you.


I know what is factorial. But i am not sure about inbuilt factorial function in python.


We are not using any built in functions. Write one.

What is the mathematical definition?

n! = 1 * 2 * .. * (n - 1) * n

The hidden jewel in this is that 1! is 1 but then so is 0!. They both represent unity.

We can legimately initialize a starting value for n = 1.

n  = 1
n *= 2
n *= 3
n *= 4
n *= 5

== 5! == 120


Okay. Then explain me how the else statement will determine this:

a = x * factorial(x -1)

putting the values in them:

a = 4 * (4-1)
a = 4 * 3
a = 12??

Also how this will convert into a loop because we are using if and else statement.


There is obvious recursion going on here so I see no need for a running variable (a). The call stack will resolve on final return.


What do you mean by recursion?


It should be evident that range is not a go to in this problem since it forces us to modify the upper bound. I'm puirist, and hate doing these things. while gives us the inequality. That's going for it.

f = 1
while x > 0:
    f *= x
    x -= 1
return f


while x > 1
    return x * factorial(x - 1)


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.