Sitemap
Praveen Kumar

Praveen Kumar

Recursive Function In Python

Why do we use Recursive Function.,?

2 min readNov 9, 2023

--

This is not mandatory to write all functions as recursive functions but Recursive functions make the code look clean and elegant. when you are working on Sequence generation, it is very easier with recursion than using user defined functions.

What is Recursive Function.,?

A recursive function is a process in which a function calls itself directly or indirectly.

we should be very careful while writing recursive functions because it may lead to a never ending function (never terminates) and other possible case is will take excess amount of memory and processor.

will look into the syntax for recursive function


def fun_a(): <--
|
| (recursive call)
|
fun_a() ----

while Writing recursive functions we must define two things

  1. Base Case
  2. Recursive Case

Lets us take a example to observe the above two parameters.


def rec_factorial(n):
if n == 1:
return 1
else:
return n * rec_factorial(n-1)

print(rec_factorial(3))

Let’s look into the execution of the above code in the below diagram

Press enter or click to view image in full size

the above recursive function will calculate the factorial of the number when we call the function with a parameter. As you can observe in the return statement, factorial function is calling it self.

Get Praveen Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Base Case:- Base case will define when to terminate the function or when to stop executing the function. As we can see in the above example when the ’n’ value becomes ‘1’ (n==1), then the function stops executing.

So writing this condition like when to stop executing is called Base case.

Recursive Case:- This is the part of the function where it calls itself with modified arguments.

It defines how the problem can be broken down into smaller subproblems.

Note:- when you are writing base case pay attention.

Thanks for reading the blog. See you in next blog.

DO FOLLOW ME ON INSTAGRAM :- learn_with_praveen

— — — — — — — — — — — — — — — Praveen Writings

--

--