Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Recursion in Python:-

Python Recursion

Python Recursion — Complete Guide with Examples

Recursion is a programming technique where **a function calls itself** to solve smaller sub-problems of the original task. Every loop or repetitive task can also be rewritten using recursion.

Formal Definition: A function is considered recursive when it calls itself inside its own function body.

def xyz():
    xyz()   # recursive call

This creates an infinite recursion unless a base condition is used.


Why Recursion?

  • To break complex problems into smaller subproblems
  • Used in tree traversal, graphs, mathematics, searching, sorting, dynamic programming
  • Makes code shorter and cleaner

But recursion must always include a BASE CONDITION:

if some_condition:
    return value

Example 1 — Simple Recursive Function

def xyz(num):
    print("number =", num)
    if num > 10:       # base condition
        return
    xyz(num + 1)       # recursive call

xyz(1)

This program will print numbers from 1 to 11.


Recursion Flow Diagram (Simplified)

xyz(1)
 └── xyz(2)
      └── xyz(3)
           └── ...
                └── xyz(11) → stops (base condition)

Example 2 — Sum of Numbers (1 to n) Using Recursion

def fun(num):
    if num == 0:          # base condition
        return 0
    else:
        return num + fun(num - 1)

x = fun(5)
print(x)

Output:

15

Deep Explanation — How Recursion Works Internally?

Whenever a recursive call is made, Python stores the current state in a stack (called the call stack).

For sum(5)

fun(5)
 → 5 + fun(4)
        → 4 + fun(3)
               → 3 + fun(2)
                      → 2 + fun(1)
                             → 1 + fun(0)
                                     → returns 0
Then Python begins returning values backward (unwinding phase):
fun(1) = 1 + 0 = 1  
fun(2) = 2 + 1 = 3  
fun(3) = 3 + 3 = 6  
fun(4) = 4 + 6 = 10  
fun(5) = 5 + 10 = 15

Advantages of Recursion

  • Simplifies complex logic (tree, graphs, DFS, BFS)
  • Code is shorter and cleaner
  • Useful for mathematical formulas: factorial, Fibonacci, power, etc.

Disadvantages of Recursion

  • Consumes more memory (stack frames)
  • Slower than loops in many cases
  • Can cause RecursionError if base condition missing or too deep

Most Common Use Cases of Recursion

  • Factorial
  • Fibonacci series
  • Tree traversal (pre, post, in-order)
  • Graph traversal (DFS)
  • Searching and sorting (merge sort, quick sort)
  • Mathematical sequences

Assignments with Extended Depth

1) WAP to calculate factorial using recursion

def fact(n):
    if n == 0 or n == 1:     # base condition
        return 1
    return n * fact(n - 1)

print(fact(5))

Flow:

fact(5)
 → 5 * fact(4)
 → 4 * fact(3)
 → 3 * fact(2)
 → 2 * fact(1)
 → returns 1

2) WAP to display Fibonacci series using recursion

Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13 ...

def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)

num = 10
for i in range(num):
    print(fib(i), end=" ")

Important Note:

Recursive Fibonacci has exponential time complexity O(2ⁿ). Better version uses memoization.


3) WAP to calculate sum of even and odd numbers from 1 to 50 using recursion

def sumEvenOdd(n, evenSum=0, oddSum=0):

    if n == 0:
        return evenSum, oddSum

    if n % 2 == 0:
        evenSum += n
    else:
        oddSum += n

    return sumEvenOdd(n-1, evenSum, oddSum)

even, odd = sumEvenOdd(50)
print("Even Sum =", even)
print("Odd Sum  =", odd)

Output:

Even Sum = 650
Odd Sum  = 625

Bonus Deep Explanation — When Should You Prefer Recursion?

Use Recursion When:

  • The problem is naturally recursive (tree, graph, hierarchical data)
  • Simplification is more important than performance
  • You require clean and mathematical representation

Avoid Recursion When:

  • Performance is critical
  • The depth of recursion may cross Python's recursion limit
  • A loop is simpler and faster

Conclusion

Recursion is a powerful concept that turns a complex problem into a set of smaller tasks. Understanding base conditions and stack behavior is essential for writing efficient recursive programs.

Post a Comment

16 Comments

  1. #WAP to calculate factorial using recursion?

    def fun(num):
    if num ==1:
    return num
    else:
    return num*fun(num-1)
    x=fun(5)
    print(x)

    ReplyDelete
  2. #WAP to display Fibonacci series using recursion?

    def fun(num,i,j):
    if num==0:
    exit(0)
    else:
    k=i+j
    print(k)
    i=j
    j=k
    return fun(num-1,i,j)
    fun(10,-1,1)

    ReplyDelete
  3. #WAP to calculate the sum of even numbers and the odd numbers of 1 to 50 using recursion?

    def recursion(k,n,a,b):
    if(k<=n):
    if(k%2==0):
    a=a+k;
    else:
    b=b+k;
    else:
    print("Even no's sum is :",a,"Odd no's sum is :",b);
    return 0
    return recursion(k+1,n,a,b);
    k=recursion(1,50,0,0);

    ReplyDelete
  4. #WAP to display Fibonacci series using recursion?


    def fibo(n):
    if n==1:
    return 0
    if n==2:
    return 1
    return fibo(n-1)+fibo(n-2)
    n=int(input("enter number"))
    for i in range(1,n+1):
    print(fibo(i))

    ReplyDelete
  5. #Shivam Shukla
    #1) WAP to calculate factorial using recursion?
    def fact(k):
    if(k==1):
    return k;
    else:
    return k*fact(k-1)
    val=fact(5)
    print(val)

    ReplyDelete
  6. #Shivam Shukla
    #2) WAP to display Fibonacci series using recursion?
    #0 1 1 2 3 5 8 13 21 .......

    def fib(times,a,b,lst):
    k=a+b
    lst.append(k);
    if(times==1):
    return lst
    return fib(times-1,b,k,lst);

    times=int(input("how many number's haved input : "));
    a=-1; b=+1; lst=[];
    print(fib(times,a,b,lst));

    ReplyDelete
  7. #Shivam Shukla
    #3) WAP to calculate the sum of even numbers and the odd numbers of 1 to 50 using recursion?
    def calc(num,even,odd):
    if(num%2==0):
    even+=num;
    else:
    odd+=num;
    if(num==1):
    return(even,odd);
    return calc(num-1,even,odd);

    num=int(input("Give's a range! yaa i means 0 to where..... : "));
    even=0; odd=0;
    s=calc(num,even,odd);
    print(s)
    print("Even number's count is :",s[0]);
    print("Odd number's count is :",s[1]);

    ReplyDelete
  8. # WAP to calculate factorial using recursion?
    def fun(fac):
    if fac==1:
    return fac
    else:
    return fac*fun(fac-1)
    x=fun(5)
    print(x)

    #WAP to display Fibonacci series using recursion?
    def fibo(n):
    if n==1:
    return 0
    if n==2:
    return 1
    return (fibo(n-1)+fibo(n-2))

    n=int(input("Enter the number = "))
    for i in range (1,n+1):
    print(fibo(i))

    # WAP to find even numbers and the odd numbers using recursion?
    def evenodd(n):
    if n==0:
    return True
    if n==1:
    return False
    return evenodd(n-2)

    n=int(input("Enter the number = "))
    if evenodd(n):
    print(n,"even")
    else:
    print(n,"odd")

    #WAP to calculate the sum of even numbers and the odd numbers of 1 to 50 using recursion?
    def oddeven(i,n,a,b):
    if i<=n:
    if i%2==0:
    a=a+i
    else:
    b=b+i
    else:
    print("Even",a,"odd",b)
    return 0
    return oddeven(i+1,n,a,b)
    i=oddeven(1,50,0,0)




















    ReplyDelete
  9. def fun(num):
    if num==1:
    return num
    else:
    return num*fun(num-1)

    x=fun(8)
    print(x)

    ReplyDelete
  10. #WAP to calculate factorial using recursion?
    def fact(num):
    if num==1:
    return num
    else:
    return num*fact(num-1)
    n=fact(5)
    print(n)

    ReplyDelete
  11. #WAP to display Fibonacci series using recursion?
    def fib(num,a,b):
    if num==0:
    return
    else:
    c=a+b
    print(c)
    a=b
    b=c
    return fib(num-1,a,b)
    fib(15,-1,1)

    ReplyDelete
  12. #WAP to calculate the sum of even numbers and the odd numbers of 1 to 50 using recursion?
    def even(num):
    if num>0:
    even(num-1)
    print(2*num)

    even(25)

    ReplyDelete
  13. #WAP to calculate factorial using recursion?

    def fun(num):
    if num==1:
    return num
    else:
    return num*fun(num-1)
    x=fun(4)
    print(x)

    ReplyDelete
  14. #PROGRAM TO CHECK PRIME NUMBER USING RECURSION
    def prime(n, i=2):
    if n == i:
    return "prime number"
    elif n % i == 0:
    return "Not prime"
    return prime(n, i + 1)
    print(prime(5))

    ReplyDelete
  15. #square cube
    def fun(n):
    print(n*n, n*n*n)
    if (n):
    return 1
    return fun(n)
    fun(5)

    ReplyDelete
  16. #PROGRAM TO CHECK PRIME NUMBER USING RECURSION

    def prime(n, i=2):
    if n == i:
    return 1
    elif n % i == 0:
    return 0
    return prime(n, i + 1)
    n=int(input("Enter number"))
    s=prime(n)

    if s==1:
    print("Prime Number")

    if s==0:
    print("Not prime")

    ReplyDelete

POST Answer of Questions and ASK to Doubt