VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/09/beginners-guide-to-recursion-in-python/

⇱ Recursion in Python | Beginner's Guide to Recursion in Python


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Beginner’s Guide to Recursion in Python

Pinak Last Updated : 20 Sep, 2021
4 min read

This article was published as a part of the Data Science Blogathon

Introduction: 

Hello Readers, hope all of you are doing great. In this article, we will be covering all the basics needed for a beginner to start with recursion in python.

What is Recursion?  

In many programs, you must have implemented a function that calls/invokes some other function. For example :

def A():
b()

Here we see that the function β€˜A’ calls the function β€˜B’

So a basic example of recursion would be the case, when the function would call itself, in place of some other function.

A function is said to be a recursive function if it calls itself.

They are of two types: indirect and direct recursion.

When a function calls itself directly, from within its body, it is direct recursion. Example :

def rec():
rec()

On the other hand, when a function calls some other function, which in turn calls its caller function again, is called indirect recursion. Example :

def A():
B()
def B():
A()

Base Case for Recursion in Python 

Let us consider the following code :

def fun1():
print("Hello function 2")
fun2()
def fun2():
print("Hello function 1")
fun1()

Can you predict what shall be the output?

Yes, you guessed it right, the code will print endlessly !!

This is because the functions will keep on calling each other endlessly.

But does this mean, that the entire memory will be used up in the process? NO, python will return an error to prevent that and stop right there.

The error will be something like:

RuntimeError: maximum recursion depth1 exceeded...

So clearly, when using recursion, we must write a sensible code, that instructs the compiler, when to stop the process, this is where Base Case comes into play.

A Base Case is a case, whose result is known or predetermined, without any recursive calling. you will have a better understanding of a base case when u see an example.

Example to calculate the sum of β€˜n’ numbers using recursion in Python

Shown below, is the code, to calculate e the sum of first β€˜n’ numbers, using recursion.

def rec(n):
if n==1 :
return 1    # This is a Base Case
else:
return (n+rec(n-1))
last = int(input("Enter the upper limit"))
s = rec(last)
print("Sum of series from 1 to  ", last," is :", s)

The output of the above code came out to be :

Enter the upper limit 4
Sum of series from 1 to 4 is :10

In the β€˜main’ block, the rec function is called, with the value that the user entered, which in this case was 4, i.e., rec(4) was invoked initially.

 Now the control, shifts to line 1, where code of rec() begins. The variable β€˜n’ is assigned value 4.

As n==1 turns out to be false, it goes to the else part.

Line 5 calculates return value as n+rec(n-1), as n=4, it becomes 4 + rec(3)

So rec is again called with value 3. So this goes on and on until the value of n reduces to 1, and the base case is hit, and 1 is returned. No variable s gets the value 10 returned., which then prints the sum of the series in the next line.

Recursive Definition 

A Recursive definition is a definition that is made in terms of the smaller version of itself. Consider the following example :

xn = x*x*x*x…n times

Now it can be represented in terms of recursive definition as follows :

xn = x*(xn-1) for n > 1  (This is the recursive definition)

=x (for n=1) or 1 (for n=0)

Writing a recursive function 

Before you start writing a recursive function, you must know, that every recursive function must have at least two cases. They are :

1) The Base Case, that we know how to solve, which leads to the recursion to end. In other words, it is the case whose value is pre-known.

2) The Recursive Case is the more general case of the problem we are trying to solve, using a recursive call to the same function.

For example, Power (x,n) = x * Power(x, n-1)

Here , the base case would be :

Power (x,n) = 1 when n=0, or x (when n=1)

The base case in a recursive function, MUST BE REACHABLE!

Computing GCD Recursively  

We can efficiently compute the gcd of two numbers using the concept of recursion. Note that this holds for positive p and q.

If p>q,

the gcd of p and q is the same as the gcd of p and p%q. That is our python code to compute gcd.

def gcd(p,q):

   if q== 0:

        return p

   return gcd (q,p%q)

Here, the base case is when q is 0, with gcd (p,0) = p. To see that the reduction step converges to the base case, observe that the second input strictly decreases in each recursive call since       p%q <q. If p<q the first recursive call switches arguments.

This recursive approach to calculate the GCD of two numbers is called .

Recursion versus Iteration  

A simple yet crisp difference between the two would be  :

In iteration, the block of code is executed repeatedly, using the same memory space. That is, the memory space, once allocated, is used for each pass of the loop.

On the other hand, in recursion, since it involves a function call at each step, fresh memory is allocated for each recursive call. For this reason, because of the function call overheads, the recursive function runs slower than its iterative counterpart.

Disadvantages of recursion  

Recursion, along with it, also brings some of its own disadvantages. Some are :

  1. It is slower as compared to iteration.
  2. Logical but difficult to find the error, if any exists.
  3. Requires extra storage space this is because, for every recursive call, separate memory is allocated for the variables.
  4. Recursive functions often throw a Stack Overflow Exception when processing or operations are too large.

Ending Notes  

That ends your journey through recursion, a programming technique in which a function calls itself. Recursion, as you saw, is rightfully isn’t appropriate for every task, and is not always an alternative to iteration. But some programming problems need it. In those situations, it’s a great technique to have at your disposal.

About the Author : 

Hey there, I am Pinak Datta, currently, a second-year student, pursuing Computer Science Engineering from Kalinga Institute of Industrial Technology, Bhubaneswar. My interests include Web development, Competitive Coding, and a bit of Machine Learning too. Please feel free to connect with me through my socials. I always love to have a chat with similarly minded people.

  1. Linked-in
  2. Instagram
  3. Facebook
  4. Mail
The media shown in this article on recursion in Python are not owned by Analytics Vidhya and are used at the Author’s discretion.

Hi, I'm Pinak Datta, currently pursuing my B.Tech in Computer Science and Engineering from Kalinga Institute of Industrial Technology. I'm in my third year of study and I've always had a keen interest in technical writing and software development. I love to develop programs and scripts using Python and have worked on several projects in this language.

Apart from my academic pursuits, I've also participated in various hackathons and coding competitions. These experiences have allowed me to showcase my creativity and problem-solving abilities in the field of computer science.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner