Complete the following recursive function for calculating the factorial of a number.
def fact(num):
if(num==0):
return 1
else:
return _________
Answers
def fact(num):
if(num==0):
return 1
else:
return (num * fact(num - 1))
With the above code, the factorial is calculated recursively.
The terminal condition is if (num = 0) it will return 1 and the function terminates.
It will return to the called function.
For an example, fact(3) is called as follow
fact(3) calls fact(2).
fact(2) calls fact(1)
fact(1) calls fact(0)
fact(0) goto the if loop and returns 1.
fact(1), returns 1*1 to fact(2)
fact(2) returns 2*1 to fact(3)
fact(3) returns 3*2 finally.
Recursive function looks like this:
def fact(num):
if(num==0):
return 1
else:
return num*fact(num-1)
Note: In this function accepts the number as an argument.
Explanation:
Here, we have a function which will call itself. Number is passed as an argument to recursive function.
The condition is that if the entered number is 0,it returns 1.
Otherwise the function is called recursively with the num - 1 multiplied by the num itself.
The result is returned.
What is recursive function:
Recursion is a technique in which a function calls itself. Recursive function performs the tasks by dividing it into subtasks.
Hope it helps!