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.
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
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
We can create a function to calculate the sum of the first N natural numbers using the formula.
For example,
sum_of_natural_numbers
that takes one parameter n
.n * (n + 1) // 2
to calculate the sum of the first N natural numbers.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)
Sum of the first 10 natural numbers is 55