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.