Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Python Recursive Function Concept: Python Tutorial for Beginners

Updated on 19 November, 2024

5.76K+ views
7 min read

In the world of computer science, recursion refers to the technique of defining a thing in its own terms. In other words, a recursive function calls itself for processing. In this article, we will understand the concept of recursive function in Python, a widely-used programming language of the 21st century. 

What is Python Recursion?

In Python, a group of related statements that perform a specific task is termed as a ‘function.’ So, functions break your program into smaller chunks. And it is common knowledge that a function can call other functions in Python.

But some other functions can call themselves. These are known as recursive functions. Consider two parallel mirrors placed facing one another. Now, any object that is kept between the mirrors would be reflected recursively.

Let us go into detail about the recursive function to understand its working clearly. 

Learn data science to gain edge over your competitors

The Recursive Function

We know that a recursive function in Python calls itself as it is defined via self-referential expressions, i.e., in terms of itself. It keeps repeating its behaviour until a particular condition is met to return a value or result. Let us now look at an example to learn how it works. 

Also read: Python Interview Questions & Answers

Suppose that you want to find out the factorial of an integer. Factorial is nothing but the product of all numbers, starting from 1 to that integer. For instance, the factorial of 5 (written as 5!) would be 1*2*3*4*5*6, i.e., 720. We have a recursive function calc_factorial(x), which is defined as follows:

def calc_factorial(x):

#Recursive function to find an integer’s factorial 

if x == 1:

return 1

else

return (x * calc_factorial(x-1))

What would happen if you call this function with a positive integer like 4? Well, each function call will add a stack frame until we reach the base case (when the number reduces to 1). The base condition is required so that the recursion ends and does not go on indefinitely. So, in the given case, the value 24 will be returned after the fourth call. 

Our learners also read: Top Python Free Courses

Implementation of Recursive Function in Python

There can be varied applications of recursive functions in Python. For instance, you want to make a graphic with a repeated pattern, say a Koch snowflake. Recursion can be used for generating fractal patterns, which are made up of smaller versions of the same design.

Another example is that of game-solving. You can write recursive algorithms for solving Sudoku and numerous complex games. Recursion is most commonly used in searching, sorting, and traversal problems. 

A striking feature of the function is that recursive implementation allows backtracking. So, recursion is all about building a solution incrementally and removing those solutions that do not satisfy the problem constraints at any stage. Two things are necessary to achieve this – maintaining state and suitable data structure. Read on to get familiar with these terms. 

Read: Python Developer Salary in India

Maintaining the state

Each recursive call in Python has its own execution context. While dealing with recursive functions in Python, you have to thread the state through each recursive call. With this, the current state becomes a part of the current call’s execution context. You can also keep the state in global scope. 

For example, if you are using recursion to calculate 1+2+3+4+…….+10. Here, the current number you are adding and the sum accumulated to that point forms the state that you need to maintain. Maintaining the state involves passing the updated current state as arguments through each call. Here’s how you can do it. 

def sum_numbers(current_number, accumulated_sum)

#Base case

#Return final state

if current number==11:

return accumulated_sum

#Recursive case

#Thread the state through recursive call

Else:

return sum_numbers(current_number + 1, accumulated_sum + current_number)

Alternatively, you can use the global mutable state. To maintain state using this method, you keep the state in global scope. 

 current_number = 1

 accumulated_sum = 0

def sum_numbers():

global current_number

global accumulated_sum

#Base case

if current_number==11

  return accumulated_sum

 #Recursive case

 else:

  accumulated_sum = accumulated_sum + current_number

  current_number = current_number + 1

  return sum_numbers()

Recursive Data Structures

A data structure is considered recursive if it can be defined in terms of smaller and simpler versions of itself. Examples of recursive data structures include lists, trees, hierarchical structures, dictionaries, etc. A list can have other lists as elements. A tree has sub-trees, leaf nodes, and so on.

It is important to note here that the structure of recursive functions is often modeled after the data structures that it takes as inputs. So, recursive data structures and recursive functions go hand in hand. 

Recursion in Fibonacci Computation 

Italian mathematician Fibonacci first defined the Fibonacci numbers in the 13th century to model the population growth of rabbits. He deduced that starting from one pair of rabbits in the first year, the number of rabbit pairs born in a given year equals the number of rabbit pairs born in each of the last two years. This can be written as: Fn = Fn-1 + Fn-2 (Base cases: F0=1 and F1=1).

When you write a recursive function to compute the Fibonacci number, it can result in naive recursion. This happens when the definition of the recursive function is naively followed, and you end up recomputing values unnecessarily. To avoid recomputation, you can apply lru_cache decorator to the function. It caches the results and saves the process from becoming inefficient. 

Read more: Top 10 Python Tools Every Python Developer Should Know

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

Pros and Cons of Recursive

Recursion helps simplify a complex task by splitting it into sub-problems. Recursive functions make cleaner code and also uncomplicate sequence generation. But recursion does not come without its limitations. Sometimes, the calls may prove expensive and inefficient as they use up a lot of time and memory. Recursive functions can also be difficult to debug. 

Wrapping Up

In this article, we covered the concept of Python recursion, demonstrated it using some examples, and also discussed some of its advantages and disadvantages. With all this information, you can easily explain recursive functions in your next Python interview!

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Frequently Asked Questions (FAQs)

1. Why is recursion so important?

If you are a programmer, then it is very important for you to think recursively. The reason is that recursive functions will help you to break down a complex program into a smaller one. You will also notice that recursive solutions are much simpler to read as compared to iterative ones.
You will often see that certain programs take up a huge amount of space and lines of code for functioning. There are several scenarios where these programs can be simplified by adding a recursive function so that the function is called again and again whenever it is required. So, you won't have to write so many extra lines of code, and the work also gets done effectively.

2. What are the applications of recursion?

There are plenty of practical applications of recursion seen in both computing functions and real life. Without the use of recursion, it is not possible to express certain math functions such as Fibonacci sequence, Ackermann function, for determining whether a number is a palindrome or not, draw a type of fractal, and much more.
There are several software and apps which are built through these math functions. For instance, Candy Crush uses these math functions and recursion for the generation of a combination of tiles. Other than that, chess is also a classic example of the application of recursion. A majority of searching algorithms that we utilize today also make use of recursion.

3. What are the fundamental rules of recursion?

Recursive functions are the ones that can call themselves for solving a complex problem by simplifying it in different small steps. There are four fundamental rules of recursion. There has to be a base case that can be solved without the help of recursion. Every case that should be solved recursively should always make progress towards the base case. Use proof by induction in the designing rule for assuming that all the recursive calls work. You should never use separate recursive calls for solving the same instance of the problem. Instead, you should go with dynamic programming.