Skip to content

Sum of n natural numbers in Python using recursion | Example code

  • by

Using an if-else statement with the function you can write a recursion program for the Sum of n natural numbers in Python.

Note: To prevent it from falling into an infinite loop, a recursive call is placed in a conditional statement.

Example Sum of n natural numbers in Python using recursion

A simple example code finds the sum of natural using a recursive function.

def recur_sum(n):
    if n <= 1:
        return n
    else:
        return n + recur_sum(n - 1)


num = 15

if num < 0:
    print("Enter a positive number")
else:
    print("The sum is", recur_sum(num))

Output:

Sum of n natural numbers in Python using recursion

Do comment if you have any doubts or suggestions on this Python sum topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *