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 Set difference_update()
Python slice()
Python Matrices and NumPy Arrays
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Sort Words in Alphabetic Order
Python list()
Python String format()
Python pass statement
Python Dictionary clear()
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python exec()
Python Iterators
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python getattr()
Python Sets
Python Inheritance
Python Program to Swap Two Variables
Python Program to Reverse a Number
Python String encode()
Python String rsplit()
Python timestamp to datetime and vice-versa
Python String maketrans()
Python zip()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Create Pyramid Patterns
Python Program to Compute all the Permutation of the String
Python Program to Display Powers of 2 Using Anonymous Function
Python String find()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python bool()
Python Program to Check if a Key is Already Present in a Dictionary
Python hash()