# Factorial

#1

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
else:
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)

#2

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

#3

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

#4

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

#5

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

else:
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.

#6

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.

#7

What do you mean by recursion?

#8

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``````

#9

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

#10

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