Python Functions
Python program to find the sum of natural numbers using recursion
Description: Write a Python program to find the sum of the first n natural numbers using recursion.
Rules and hints:
- A recursive function calls itself.
- Every recursive function needs a stopping (base) case.
Python program for the sum of natural numbers using recursion
def sum_to(n):
if n == 0:
return 0 # base case
return n + sum_to(n - 1)
print(sum_to(5))
print(sum_to(10))
Output:
Tutorials Class - Output Window
15
55
How it works
sum_to(5)returns 5 +sum_to(4), and so on, down tosum_to(0)which returns 0.- The results come back as 0, 1, 3, 6, 10 and 15.
- Without the base case the function would never stop and Python would raise a
RecursionError.
See the Recursion section of Python Functions.