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 Sum of n natural numbers in Python.

Note: In order to prevent it from falling in an infinite loop, a recursive call is placed in a conditional statement.

Example Sum of n natural numbers in Python using recursion

Simple example code finds the sum of natural using 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 (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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.