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))
Do comment if you have any doubts or suggestions on this Python sum topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.