Skip to main content

Python: Recursion (Recursive Function)

In Python, Recursion is the process of defining something in terms of itself. It is a common mathematical and programming concept. It is the process in which a function can directly or indirectly call itself.

Advantages of using recursion

  • It makes  the code look more clean and elegant.
  • Sequence creation is simpler through recursion than utilizing any nested iteration.
  • Using recursion we can break complicated program into sub-programs.

Disadvantages of using recursion

  • A lot of memory and time is taken through recursive calls which makes it expensive for use.
  • Recursive functions are challenging to debug.
  • The reasoning behind recursion can sometimes be tough to think through.

Syntax:

def func(): 
    ...
    ... (recursive call)
    ...
    
// calling function
func() 

Example:

def is_prime(i,n):
    if n == i:
        return 0
    else:
        if(n % i == 0):
            return 1
        else:
            return is_prime(i+1, n)

n = int(input("Enter your Number:"))

if(is_prime(2, n) == 0):
    print("It is a Prime Number.")
else:
    print("It is not a Prime Number.")

Output:

Enter your Number:4
It is not a Prime Number.
Tags
Submitted by devanshi.srivastava on July 6, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.