Python Program to Find Sum of Natural Numbers by Recursion
This Python program finds the sum of first n natural numbers using a recursive function or recursion.
Python Source Code: Sum of Natural Numbers Using Recursion
# Sum of first n natural numbers using recusrion
# Recursive function definition
def rec_sum(n):
s = 0
if n<=0:
return 0
return n + rec_sum(n-1)
# Reading number from user
number = int(input('Enter number: '))
# Displaying sum of first n natural numbers
print('Sum of first %d natural numbers is %d' %(number,rec_sum(number)))
The output of the above program is:
Enter number: 20 Sum of first 20 natural numbers is 210