Python Tutorials

Python Programs

Python Find Sum of First N Natural Numbers using Recursion


Python Find Sum of First N Natural Numbers using Recursion

In this tutorial, we will learn how to find the sum of the first N natural numbers using recursion in Python. We will cover the basic concept of recursion and implement a recursive function to calculate the sum.


What is the Sum of Natural Numbers

The sum of the first N natural numbers is the sum of all positive integers from 1 to N. This can be calculated recursively by adding the current number to the sum of the previous numbers.


Syntax

The syntax to find the sum of the first N natural numbers using recursion in Python is:

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


Finding the sum of the first N natural numbers using recursion

We can create a recursive function to calculate the sum of the first N natural numbers.

For example,

  1. Define a function named sum_of_natural_numbers that takes one parameter n.
  2. Check if n is equal to 1. If true, return 1 (base case).
  3. Otherwise, return n plus the result of calling sum_of_natural_numbers with n - 1 (recursive case).
  4. Call the function with a sample value and print the result.

Python Program

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

# Find the sum of the first 10 natural numbers
result = sum_of_natural_numbers(10)

# Print the result
print('Sum of the first 10 natural numbers is', result)

Output

Sum of the first 10 natural numbers is 55