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.
- Log in to post comments