Python: Find the Sum of Natural Numbers Using Recursion

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

In this blog post, we will learn how to write a Python program to find the sum of natural numbers using recursion.

Recursion is a programming technique where a function calls itself. It is especially useful for tasks that can be defined in terms of similar sub-tasks. Calculating the sum of natural numbers is a great example to showcase the power of recursion.

2. Program Overview

1. Define a recursive function that computes the sum of the first N natural numbers.

2. Get the value of N from the user.

3. Call the recursive function and display the result.

3. Code Program

# Python program to find the sum of natural numbers using recursion def sum_of_natural_numbers(n): """Function to compute the sum of the first n natural numbers using recursion.""" # Base condition if n == 1: return 1 else: return n + sum_of_natural_numbers(n - 1) # Get the number of natural numbers to sum num = int(input("Enter the number of natural numbers you want the sum for: ")) # Validate the input if num < 1: print("Please enter a positive number.") else: print(f"The sum of the first {num} natural numbers is:", sum_of_natural_numbers(num)) 

Output:

Enter the number of natural numbers you want the sum for: 5 The sum of the first 5 natural numbers is: 15 

4. Step By Step Explanation

1. We start by defining our recursive function sum_of_natural_numbers. This function will be used to compute the sum of the first n natural numbers.

2. The base condition for our recursion is when n equals 1. At this point, we simply return 1.

3. If n is not equal to 1, we recursively call our function with n-1 and add n to the result. This approach breaks down the problem into smaller sub-problems.

4. We then request the user to input the number num for which they want to find the sum of natural numbers.

5. If the user inputs a number less than 1, we notify them to enter a positive number.

6. For a valid positive number, we call our recursive function and display the result.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare