In this article, we will learn how to write a Python program to find the sum of natural numbers using recursion. We will also discuss what recursion is and how it works in Python.

Recursion is a technique in which a function calls itself. When a function calls itself, it is said to be recursive. Recursion is a powerful technique that is used in many programming languages. It is used to solve problems that can be broken down into smaller problems of the same type.

To find the sum of natural numbers using recursion, we need to first understand what natural numbers are. Natural numbers are the numbers that we use to count objects. They are positive integers, starting from 1. For example, 1, 2, 3, 4, 5, and so on are natural numbers.

Now, let’s look at the Python program to find the sum of natural numbers using recursion.

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

# Taking input from the user
num = int(input("Enter a number: "))

# Checking if the number is positive
if num < 0:
   print("Enter a positive number")
   print("The sum of natural numbers from 1 to", num, "is", sum_of_natural_numbers(num))


Let's break down the above code:

  • We define a function called sum_of_natural_numbers that takes an argument n.
  • In the function, we have an if statement that checks if n is less than or equal to 1. If it is, we return n.
  • If n is greater than 1, we return n plus the result of calling sum_of_natural_numbers with n-1 as the argument.
  • We take input from the user and check if the input is positive.
  • If the input is positive, we call the sum_of_natural_numbers function with the input as the argument and print the result.

Let's run the Python code and see what happens:

					Enter a number: 5
The sum of natural numbers from 1 to 5 is 15


The program correctly calculates the sum of natural numbers from 1 to 5, which is 15.

Now, let’s discuss how recursion works in Python. When a function calls itself, it creates a new instance of the function on the stack. The new instance has its own set of local variables and its own call stack. When the function returns, the new instance is removed from the stack and control is returned to the previous instance.

Recursion is a powerful technique, but it can be dangerous if not used correctly. If a recursive function calls itself too many times, it can cause a stack overflow error. Therefore, it is important to ensure that a recursive function has a base case that will eventually be reached.

Thanks for reading. Happy coding!