Recursion in Python

Recursion in Python

Β·

2 min read

Namaste Coders πŸ‘©β€πŸ’»

Before starting have a glance on the below article to know about functions in Python πŸ‘‡

Built-in Functions User Defined Functions Lambda Functions

What is Recursion πŸ€”?

Recursion is simply self calling of a function. It is a technique of writing a function. In recursion we divide complex problem into simpler problem and than we find a solution for simpler problem which leads to solving the complex problem.

image.png

In recursion We have to think of following to solve a problem πŸ‘‡

  • Base case: It will end the recursion and will provide the required answer
  • Simpler solution: It will lead towards complex problem solution.

Stacks are used behind the scene in recursion.

Example: We are going to learn how to find the factorial of a number. Suppose we need to find factorial of 5. 5!=54321

Recursively: Let’s make a function fact(num) which will take num as a parameter.

Simpler Solution: fact(num)=num*fact(num-1)

Base Case: if num=1 return 1

# Factorial of a number recursively

def fact(num):
    if(num==1):
        return 1
    ans=num*fact(num-1)
    return ans

num=5
ans=fact(num)
print("Factorial is :",num)

#Output:
#Factorial is : 5

Here is the tree structure of recursion. First, we go forward till the base case is hit. Then, it moves backward resulting into the output

image.png

Here is the stack which is created in the memory πŸ‘‡

stack.PNG

image.png

For more reference do watch the video tutorial

Factorial

Fibonnaci Numbers

P.S. : Will continue with the functions and discuss more in upcoming articles. Stay tunedπŸ‘§

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharingπŸ‘©

Keep coding

Python blogs

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg's blog by becoming a sponsor. Any amount is appreciated!

Β