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.
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.
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)
We can create a recursive function to calculate the sum of the first N natural numbers.
For example,
sum_of_natural_numbers
that takes one parameter n
.n
is equal to 1. If true, return 1 (base case).n
plus the result of calling sum_of_natural_numbers
with n - 1
(recursive case).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)
Sum of the first 10 natural numbers is 55