Python

Python Program to Find Sum of Natural Numbers Using Recursion1 min read

Write a program to Find Sum of Natural Numbers Using Recursion in Python

Code:




This Python program uses a recursive function “recur_sum()” to find the sum of natural numbers up to a given number “n”. The function takes an input argument “n” and checks if it is less than or equal to 1. If it is, the function returns the value of “n” which represents the sum of natural numbers up to 1. If “n” is greater than 1, the function returns the value of “n” plus the sum of natural numbers up to “n-1” which is calculated by calling the function recursively.

The program also takes input from the user in the form of an integer using the “input()” function and assigns it to the variable “num”. If the input number is less than 0, the program prints “Enter a positive number”. If the input number is greater than or equal to 0, the program calls the “recur_sum()” function with the input number as the argument and prints “The sum is”, followed by the value returned by the function.

Example output:

Leave a Comment