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 strftime()
Python String translate()
Python Program to Print Colored Text to the Terminal
Python Set pop()
Python Program to Find LCM
Python delattr()
Python String format_map()
Python Object Oriented Programming
Python Program to Check If Two Strings are Anagram
Python input()
Python String splitlines()
Python tuple()
Python compile()
Python List insert()
Python String rpartition()
Python Program to Copy a File
Python Statement, Indentation and Comments
Python String strip()
Python Program to Convert Kilometers to Miles
Python Program to Find ASCII Value of Character
Python Data Types
Python Custom Exceptions
Python Sets
Python hash()
Python String isidentifier()
Python List index()
Python all()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Set discard()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Catch Multiple Exceptions in One Line
Python min()