Python Tutorials

Python Programs

Python Find the Sum of First N Natural Numbers


Python Find the Sum of First N Natural Numbers

In this tutorial, we will learn how to find the sum of the first N natural numbers in Python. We will cover the basic formula and implement it in a Python function.


What is the Sum of Natural Numbers

The sum of the first N natural numbers is the sum of all positive integers from 1 to N. This can be calculated using the formula:

Sum = N * (N + 1) / 2


Syntax

The syntax to find the sum of the first N natural numbers in Python is:

def sum_of_natural_numbers(n):
    return n * (n + 1) // 2


Finding the sum of the first N natural numbers

We can create a function to calculate the sum of the first N natural numbers using the formula.

For example,

  1. Define a function named sum_of_natural_numbers that takes one parameter n.
  2. Use the formula n * (n + 1) // 2 to calculate the sum of the first N natural numbers.
  3. Return the calculated sum.
  4. Call the function with a sample value and print the result.

Python Program

def sum_of_natural_numbers(n):
    return n * (n + 1) // 2

# Find the sum of the first 10 natural numbers
result = sum_of_natural_numbers(10)

# Print the result
print('Sum of the first 10 natural numbers is', result)

Output

Sum of the first 10 natural numbers is 55