Python Program to Find Sum of Natural Numbers Using Recursive Function

In this example, we will write a program that calculates the sum of natural numbers using a recursive function in Python. To better understand this example, make sure you have knowledge of the following tutorials:-

Python Program to Find Sum of Natural Numbers Using Recursive Function

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

num = int(input("Enter a number: "))
print("The sum is: ", sum(num))

The output of the above program is:-

Enter a number: 10
The sum is: 55
Program Explanation:-
The input() function takes input from the user and int() function converts its type to an integer as Python return string from input function. Here, we define a recursive function sum() that takes an argument which is an integer number. The base condition for recursion is defined and if the input number is less than or equals to 1, the number is returned, else we return the same function call with number decremented by 1. In this way, the recursive function works in Python that can calculate the sum of natural numbers.
SHARE Python Program to Find Sum of Natural Numbers Using Recursive Function

You may also like...

1 Response

  1. Really cheers for all of your contributions i have some doubts in Django forms can you post anything regarding that in this site. Looking forward for your reply.

Leave a Reply

Your email address will not be published.

Share