Recursive Function in Python

In this class, we discuss the Recursive Function in Python.

For Complete YouTube Video: Click Here

Recursive Function

The reader should have prior knowledge of the function and how memory is allocated to function. Click here.

Recursive Function:

Function calling itself is a recursive function.

Let’s take an example and understand the recursive function and how recursive functions execute.

def f(x):
     if x>0:  ------- line1
        f(x-1) ------line 2
        print(x) ----line 3
a=5
f(a)
Output:
1
2
3
4
5

In the above example. We have an if conditional statement.

If the condition is true, the function calling the same function with parameter x-1.

For better understanding, line numbers are given to the program.

Recursive Function in Python
Recursive Function Call in Stack

How memory allocates to recursive functions is shown in the above diagram.

Whenever a function is called. The function is assigned a space in the stack to save its local variables.

When the function is completed, it’s execution. The space allocated in the stack is removed.

Example Explanation

In the example, the First time, the function is called with the value 5.

argument x is taking reference to the integer value 5.

To maintain the reference value of integer object 5. Space is assigned in the stack.

The function starts executing, and the if condition satisfied. Now the function called again with value 4.

New space is assigned to this called function in the stack.

The previous function not yet completed. So last function space is still available in the stack memory.

The memory is shown in the above diagram.

The function called second time starts execution.

The remaining code in the first time called function will continue execution after completing the second called function.

The second called function will satisfy the if condition and again call the function with x-1 value.

Function calling repeats until the condition in the if statement is false.

Recursive functions execute as mentioned above.

The output displayed by the program. 1,2,3,4,5.

The concept of recursive function will understand better from the video.