# Python Program to find Sum of n Natural Numbers

*Summary:*

Natural numbers are those numbers which start with 1 and goes up to infinity. It is very easy to find the sum of n natural numbers in python using simple logic.

## Python code: Find the sum of n natural numbers using while loop

This is general logic to find the sum of n natural numbers that will work with almost all languages.

Copy

```
#Take input and convert to integer
n = int(input("Enter number of terms to sum: "))
#Save a copy for further use
ncopy = n
totalSum=0
# If n is negative then print error (it will cause infinite loop)
if(n<0):
print("You cannot enter a negative value.")
else:
while(n!=0):
totalSum = totalSum+n
n = n-1
print("Sum of first {0} natural numbers is {1}".format(ncopy,totalSum))
```

Output

Enter number of terms to sum: 5 Sum of first 5 natural numbers is 15

The logic of this python program is simple.

Line 2: We take the input and convert it to an integer.

Line 4: Save a copy of n variable for further use.

Line 7: We check if the input given is negative, if it is negative then we print an error message and terminate because input must be positive.

Line 10: If n is positive then this while loop runs until n becomes 0. Each iteration of the loop add the number to the `totalSum`

and decrease its value by 1.

Line 13: We print the `totalSum`

value.

## Python Code: Find the sum of n natural numbers using formula

There are multiple ways to solve any problem. Some ways are easy to implement if you know about them.

We can also find the sum of n natural numbers by using the basic mathematics formula n*(n+1)/2, which is generally used in number and series of maths.

Copy

```
#Using formula
n = int(input("Enter number of terms to sum: "))
totalSum = n*(n+1)/2 # return a float value
print("Sum of first {0} natural numbers is {1}".format(n,int(totalSum)))
```

## One line solution in Python (Advanced)

Here is the beauty of Python.

Python allows us to unleash our creativity for using these features.

Copy

`print(sum([i for i in range(1, int(input("Enter n: "))+1)]))`

Here is the step by step breakdown of the python code.

Step 1: Take the input and convert to integer.

Step 2: You can learn more about this list comprehension from here.

Copy

`[i for i in range(1, int(input("Enter n: "))+1)]`

Output

Enter n: 5 [1, 2, 3, 4, 5]

Step 3: The `sum()`

function takes an iterable (list, tuple, dictionary etc.) and returns sum of all its elements.

Step 4: Print the sum returned from the `sum(`

) function.

Related Python Programs: