View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
python

Python Tutorials - Elevate You…

  • 199 Lessons
  • 33 Hours

Sum of n Natural Numbers in Python

Updated on 23/01/20257,776 Views

The sum of n natural numbers refers to the total when you add all natural numbers from 1 to n. This sum can be calculated efficiently using a formula, but it’s also useful to know how to do it with loops.

In this guide, you’ll learn how to compute the sum of n natural numbers in Python. You'll see how the sum of n numbers in Python using for loop works in practice and much more. 

By the end you'll be able to apply a number of methods for calculating sums, improving your coding flexibility and problem-solving skills. 

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

What Are Natural Numbers?

Natural numbers are the set of positive integers starting from 1 and going on infinitely (1, 2, 3, 4, 5, …). These numbers are often used for counting and ordering. For example, if you are counting the number of students in a class, you would use natural numbers (1, 2, 3, ...).

In mathematics, the natural numbers are often denoted by the symbol N, and they don’t include negative numbers or fractions. Understanding this concept is essential for calculating the sum of n natural numbers in Python.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Calculate the Sum of N Numbers Using While Loop and User Input

In Python, you can also calculate the sum of numbers using a while loop. This approach is useful when you want to perform repeated actions until a specific condition is met, and it works well with user input.  

Let’s write a Python program that asks the user for the number n and then calculates the sum of the first n natural numbers using a while loop. 

n = int(input("Enter a number: "))  # Take input from the user and convert it to an integer
sum_n = 0  # Initialize the sum variable
i = 1  # Start with 1 as the first natural number
while i <= n:  # Continue looping as long as i is less than or equal to n
    sum_n += i  # Add the current value of i to sum_n
    i += 1  # Increment i to move to the next natural number 
print(f"Sum of first {n} natural numbers is: {sum_n}")

Output: 

Enter a number: 5Sum of first 5 natural numbers is: 15

Explanation:

  • User Input:
    • n = int(input("Enter a number: ")): This line prompts the user to enter a number, and the input is converted to an integer using int().
  • Initializing Variables:
    • sum_n = 0: We initialize a variable sum_n to store the cumulative sum.
    • i = 1: We start counting from 1, as the sum of natural numbers begins with 1.
  • While Loop:
    • The loop continues as long as i <= n. This ensures the loop runs for the first n natural numbers.
    • sum_n += i: We add the current value of i to the sum sum_n.
    • i += 1: This increases the value of i by 1 on each iteration, moving through the natural numbers.
  • Output: After the loop finishes, we print the result using print(f"Sum of first {n} natural numbers is: {sum_n}").

Why Use a While Loop?

A while loop is ideal when you don’t know the number of iterations in advance, but you know the condition you need to meet (in this case, i <= n). It’s great for scenarios where you want to keep adding numbers until a specific limit is reached, making it flexible for user-driven calculations.

Calculate the Sum of N Numbers Using Recursion

We’ll look at how to calculate the sum of n natural numbers in Python using recursion, which allows you to break down the problem into smaller, manageable parts.  

def sum_of_n(n):
    # Base case: when n is 1, return 1
    if n == 1:
        return 1
    else:
        # Recursive case: sum of n numbers is n + sum of n-1 numbers
        return n + sum_of_n(n - 1) 
# Take input from the user
n = int(input("Enter a number: ")) 
# Calculate the sum using recursion
result = sum_of_n(n) 
print(f"Sum of first {n} natural numbers is: {result}") 

Output: 

Enter a number: 5Sum of first 5 natural numbers is: 15

Explanation:

  • The Recursive Function (sum_of_n):
    • The function sum_of_n(n) takes n as an input and returns the sum of the first n natural numbers.
    • Base case: if n == 1:: The base case is essential for stopping the recursion. When n is 1, the function returns 1 since the sum of the first 1 natural number is 1.
    • Recursive case: return n + sum_of_n(n - 1): This is where the recursion happens. The function calls itself with n-1, adding n to the result of the smaller problem (i.e., the sum of the first n-1 natural numbers).
  • User Input:
    • n = int(input("Enter a number: ")): This line takes an input from the user, and the input is converted to an integer using int().
  • Output:
    • Finally, the result of sum_of_n(n) is printed, which gives the sum of the first n natural numbers.

Why Use Recursion?

Recursion is a powerful technique for breaking down problems into smaller sub-problems. In this case, we repeatedly calculate the sum of smaller subsets of natural numbers. It’s a more mathematical approach to the problem compared to using loops. 

Calculate the Sum of N Numbers Using For Loop

One of the most common ways is to calculate sum of n numbers in python using for loop

Let’s look at an example: 

n = int(input("Enter a number: "))  # Take input from the user
sum_n = 0  # Initialize the sum variable 
# Loop through the first n natural numbers and add them to sum_n
for i in range(1, n + 1):  # range(1, n+1) includes numbers from 1 to n
    sum_n += i  # Add current value of i to sum_n 
print(f"Sum of first {n} natural numbers is: {sum_n}") 

Output: 

Enter a number: 5Sum of first 5 natural numbers is: 15

Explanation:

  • User Input:
    • n = int(input("Enter a number: ")): This line prompts the user to enter a number, which is then converted into an integer using int().
  • Initializing the Sum:
    • sum_n = 0: We start by setting sum_n to 0. This variable will hold the cumulative sum of the numbers.
  • The For Loop:
    • for i in range(1, n + 1): The range(1, n + 1) generates numbers from 1 to n (inclusive). Each number is stored in the variable i for each iteration.
    • sum_n += i: In each iteration, the current value of i is added to the running total stored in sum_n. This is the main step where the sum is calculated.
  • Final Output:
    • After the loop finishes, the final value of sum_n is printed. This represents the sum of the first n natural numbers.

Why Use a For Loop?

Using a for loop is an intuitive and efficient method to calculate the sum of n numbers. It provides clear structure and readability, which makes it ideal for beginners. The loop allows you to iterate over a range of numbers, adding each one to the sum, and it’s easy to adjust if you need to perform more complex operations.

For example, if you needed to calculate the sum of squares of the first n natural numbers, you could modify the loop like this: 

sum_of_squares = 0
for i in range(1, n + 1):
    sum_of_squares += i ** 2  # Square each number before adding
print(f"Sum of squares of first {n} numbers is: {sum_of_squares}")  

The for loop is one of the most commonly used methods to calculate the sum of natural numbers in Python, especially when the sequence is finite and you need to perform the calculation iteratively. While recursion offers an elegant solution and a good introduction to the concept of recursion, a for loop is generally more efficient and easier to understand for simple problems like summing numbers.

Calculate the Sum of N Numbers Using Formula

An efficient way to calculate the sum of n natural numbers in Python is by using a mathematical formula. This method is fast and doesn't require looping or recursion. The formula for the sum of the first n natural numbers is:

Sum = n×(n+1)

          2

This formula gives the result directly without needing to iterate through each number, making it much faster for large values of n. 

Let’s see how to implement this formula in Python. 

n = int(input("Enter a number: "))  # Take input from the user
# Using the formula for the sum of first n natural numbers
sum_n = (n * (n + 1)) // 2  # Integer division to ensure an integer result
print(f"Sum of first {n} natural numbers is: {sum_n}") 

Output: 

Enter a number: 5Sum of first 5 natural numbers is: 15

Explanation:

  • User Input:
    • n = int(input("Enter a number: ")): This line prompts the user to input a number, which is then converted into an integer using int().
  • Formula Calculation:
    • sum_n = (n * (n + 1)) // 2: This line applies the formula for the sum of the first n natural numbers:
      • n * (n + 1) calculates the product of n and n + 1.
      • // 2 performs integer division to ensure the result is an integer.
  • Output:
    • After calculating the sum using the formula, the result is printed.

Why Use the Formula?

Using the formula is the most efficient method to calculate the sum of n natural numbers, especially when n is large. It avoids the need for loops or recursion, providing a direct calculation in constant time (O(1)).

This method is particularly useful in mathematical problems where you are given a specific range and need to calculate the sum quickly. It’s also great for solving problems in competitive programming, where performance is crucial.

Comparison with Other Methods

  • For Loop: While using a for loop is simple and intuitive, it requires iteration through all numbers from 1 to n, making it slower for large values of n (O(n) time complexity).
  • Recursion: Recursion is elegant, but it can lead to performance issues with large n due to the function call stack and deeper recursion depth.
  • Formula: The formula method is by far the most efficient for calculating the sum of n natural numbers, especially when working with large numbers.

Also Read: Arithmetic Progression Formula: Everything You Need to Know

FAQs

1. What is the sum of n natural numbers in Python?

The sum of n natural numbers in Python refers to the total of numbers starting from 1 to n. You can calculate it using loops or mathematical formulas.

2. How do I calculate the sum of n natural numbers in Python?

You can calculate the sum of n natural numbers in Python using a loop, recursion, or the mathematical formula (n×(n+1)) // 2

3. What is the formula to find the sum of n natural numbers?

The formula is (n×(n+1)) // 2. It directly calculates the sum without needing loops or recursion.     

4. Can I use a for loop to calculate the sum of n natural numbers in Python?

Yes, you can use a for loop to iterate through the numbers from 1 to n and add them together. This is a simple and common method.

5. How do I calculate the sum of n numbers in Python using for loop?

You can use a for loop like this: sum_n += i where i ranges from 1 to n. Each iteration adds i to the total sum.

6. Can recursion be used to find the sum of n natural numbers?

Yes, recursion is an elegant way to calculate the sum of n natural numbers in Python by breaking down the problem into smaller subproblems.

7. What is the base case in recursion when calculating the sum of n numbers?

The base case in recursion is when n == 1, returning 1, as the sum of the first 1 number is just 1.

8. What are the benefits of using a formula to calculate the sum of n natural numbers?

Using the formula is the most efficient method, as it calculates the sum in constant time O(1) without needing loops or recursion.

9. What is the difference between using a loop and the formula for summing numbers?

The loop method iterates through numbers, making it slower for large n, whereas the formula method calculates the sum directly, offering a faster solution.

10. Can I calculate the sum of n numbers in Python using a while loop?

Yes, you can use a while loop to calculate the sum. It’s similar to the for loop but allows more flexible conditions for stopping the iteration.

11. Which method is the most efficient for calculating the sum of n numbers in Python?

The formula (n×(n+1)) // 2 is the most efficient, as it calculates the sum directly in constant time.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.