Python Program: Sum of N Natural Numbers
In this tutorial, we will be writing Python programs to find the sum of first $n$ natural numbers, i.e., $1 + 2 + 3 + 4 + ... + n$.
In our first program below, we make use of the while
loop to repeatedly add the consecutive terms to get the desired sum. Also, since we will not be dealing with negative values here, we put the if
condition for it.
import math;
n = int(input("n = "))
if n < 0:
print("Please enter a +ve number.")
else:
sum = 0
while(n > 0):
sum += n
n -= 1
print("Sum = ", sum)
We run the above program for $n = 100$ and $n = 50$ and find the sums.

We can also derive the above sum using the for .. in
loop too.
Using the Formula $\frac{n(n+1)}{2}$
But there exists a much better way to get that sum without using any loops. We will make use of the well-known formula that we learned in our basic Sequences/Series lessons involving Arithmetic Progression: $1 + 2 + 3 + 4 + ... + n$ = $\frac{n(n+1)}{2}$
The above formula is connected to a well-known legend about the childhood of Carl Friedrich Gauss (also known as "Princeps Mathematicorum"), where he added the numbers from 1 upto 100 in a matter of seconds.

The below program in Python makes use of the $\frac{n(n+1)}{2}$ formula instead of adding terms repeatedly using the while
or for .. in
loops.
import math;
n = int(input("n = "))
if n < 0:
print("Please enter a +ve number.")
else:
sum = n*(n+1)/2;
print("Sum = ", math.trunc(sum))