This is a recursive definition of the factorial function
Principle
The two main parts of a recursive function
In Computer Science, a recursive function consists of two parts:
The base case – This condition(s) that ends the recursion.
The recursive call – This is when the function calls itself
deffactorial(n):
if n ==1: # base case, the recursion ends here# could also be n == 0return1else: # recursive call, the function calls itselfreturn factorial(n-1) * n
Note: Make sure the base case is reachable, otherwise the function will run forever.
The call stack
How recursion works
Each time a function is called, a new frame is added to the call stack
The frame contains the function’s arguments and local variables
When the function returns, the frame is removed from the stack
The call stack
factorial(3):
Things to remember
Check-list for recursive functions
Base case
Stops the recursion
Defines the result for the simplest case
Recursive call
Calls the function with
The function should eventually reach the base case