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 to sum_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.


Learn more about the similar topics:
Tutorials
Python Conditional Statements
Python While Loop
Python for loop
Python Jump Statements
Exercises & Assignments
Python program to check even or odd number
Python program to find the largest of three numbers
Python program to check leap year
Python program to print multiplication table
Python program to find factorial of a number
Python program to print Fibonacci series
Python program to check prime number
Interview Questions & Answers
No Content Found.