In this program, you’ll learn to find the sum of natural numbers using recursive function.
To understand this example, you should have the knowledge of the following Python programming topics:
In the program below, we’ve used a recursive function recur_sum() to compute the sum up to the given number.
Source Code
# Python program to find the sum of natural using recursive function
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
# change this value for a different result
num = 16
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output
The sum is 136
Note: To test the program for another number, change the value of num.
Related posts:
Python Keywords and Identifiers
Python Tuple count()
Python str()
Python Program to Display Powers of 2 Using Anonymous Function
Python Set discard()
Python Program to Copy a File
Python String format()
Python Program to Multiply Two Matrices
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Machine Learning - Sebastian Raschka
Python Program to Print the Fibonacci sequence
Python Tuple
Python String format_map()
Python object()
Python divmod()
Python Program to Sort Words in Alphabetic Order
Python String isalpha()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python String strip()
Python Program to Get the Class Name of an Instance
Python Multiple Inheritance
Python Set difference()
Python del Statement
Python Program to Delete an Element From a Dictionary
Python setattr()
Python Functions
Python Program to Add Two Numbers
Python super()
Python delattr()
Python Program to Append to a File
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Find the Factors of a Number