DEV Community

Harini
Harini

Posted on

10 Simple Recursion Programs in Python

What is Recursion?

Recursion is a technique where a function calls itself to solve a smaller version of the same problem. Every recursive function must have:

  • Base Case β†’ Stops the recursion
  • Recursive Case β†’ Calls the function again with a smaller input

1. Factorial of a Number

The factorial of a number n is the product of all positive integers up to n.

def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
Enter fullscreen mode Exit fullscreen mode

2. Sum of First N Numbers

This program calculates the sum of numbers from 1 to n.

def sum_n(n):
    if n == 0:
        return 0
    return n + sum_n(n - 1)

print(sum_n(5))

Enter fullscreen mode Exit fullscreen mode

3. Print Numbers from 1 to N

Print numbers in ascending order using recursion.

def print_1_to_n(n):
    if n == 0:
        return
    print_1_to_n(n - 1)
    print(n)

print_1_to_n(5)

Enter fullscreen mode Exit fullscreen mode

4. Print Numbers from N to 1

Print numbers in descending order.

def print_n_to_1(n):
    if n == 0:
        return
    print(n)
    print_n_to_1(n - 1)

print_n_to_1(5)

Enter fullscreen mode Exit fullscreen mode

5. Fibonacci Series (Nth Term)

Each number is the sum of the previous two.

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6))

Enter fullscreen mode Exit fullscreen mode

6. Power of a Number

Calculate base^exponent using recursion.

def power(base, exp):
    if exp == 0:
        return 1
    return base * power(base, exp - 1)

print(power(2, 3))

Enter fullscreen mode Exit fullscreen mode

7. Find GCD (Greatest Common Divisor)

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

print(gcd(12, 18))
Enter fullscreen mode Exit fullscreen mode

8. Print Odd Numbers from 1 to 10

def display(num):
    if num <= 9:
        print(num, end=" ")
        display(num + 2)   

display(1)
Enter fullscreen mode Exit fullscreen mode

9. Sum of Digits

Find the sum of digits in a number.

def sum_digits(n):
    if n == 0:
        return 0
    return (n % 10) + sum_digits(n // 10)

print(sum_digits(1234))
Enter fullscreen mode Exit fullscreen mode

10. Count Digits in a Number

Count how many digits are present in a number.

def count_digits(n):
    if n == 0:
        return 0
    return 1 + count_digits(n // 10)

print(count_digits(12345))

Enter fullscreen mode Exit fullscreen mode

Top comments (0)