B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Recursion Explained with Examples | LiveCodeProgramming
Python Installation First Python Program Control Flow if...else nested if else match-case logical-operators for loops while loops break / continue Functions Defining Functions Function Arguments Function return value Lambda Function Recursion Exception Handling Exception Handling Try Except Else and Finally Raise Exception Custom Exceptions File Handling File in python Read File Write File Append File Delete File Exception Handling

Python Recursion

Recursion is a process where a function calls itself. It's used to solve problems that can be broken down into smaller sub-problems of the same type.

Recursion वह प्रक्रिया है जिसमें एक function खुद को call करता है। इसका उपयोग उन्हीं problems को solve करने के लिए किया जाता है जिन्हें छोटे-छोटे हिस्सों में divide किया जा सकता है।

How Recursion Works

Every recursive function must have a base condition that stops the recursion. Otherwise, it will run infinitely and cause an error.

हर recursive function में एक base condition होना चाहिए जो recursion को रोकता है, वरना infinite बार call होता रहेगा।

Advantages of Recursion
  • Code becomes clean and short
  • Good for problems like tree traversal, factorial, Fibonacci
Disadvantages of Recursion
  • Uses more memory due to function calls
  • Can cause stack overflow if base condition is not met
  1. Factorial of a number
    def factorial(n):
        if n == 1:
            return 1
        return n * factorial(n - 1)
    
    print("Factorial:", factorial(5))
    Output:
    Factorial: 120
  2. Fibonacci series
    def fib(n):
        if n <= 1:
            return n
        return fib(n-1) + fib(n-2)
    
    for i in range(6):
        print(fib(i), end=' ')
    Output:
    0 1 1 2 3 5
  3. Sum of first N natural numbers
    def sum_n(n):
        if n == 0:
            return 0
        return n + sum_n(n - 1)
    
    print("Sum:", sum_n(10))
    Output:
    Sum: 55
  4. Reverse a string using recursion
    def reverse(s):
        if len(s) == 0:
            return s
        return reverse(s[1:]) + s[0]
    
    print(reverse("hello"))
    Output:
    olleh
  5. Countdown using recursion
    def countdown(n):
        if n == 0:
            print("Blast off!")
        else:
            print(n)
            countdown(n - 1)
    
    countdown(5)
    Output:
    5
    4
    3
    2
    1
    Blast off!