# Find Sum of n Natural Numbers | Python

Python can be used for doing Mathematical Stuff specifically using Math Module, in this article I fill discuss How to find some of first n Natural Numbers using Python? Natural Numbers sequence start from 1 and goes up to positive infinity. So first 5 Natural Numbers will be 1, 2, 3, 4, 5 and first 10 Natural Numbers will be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Let’s for fininding sum of first 5 Natural Numbers, you need to do 1 + 2 + 3 + 4 + 5 but mathematically this summation can be sequezed in as n(n+1)/2 where n is number of Natural Numbers. Like for finding sum of first 5 natural numbers instead of doing 1 + 2 + 3 + 4 + 5, just do 5(5+1)/2 = 5(6)/2 = 15.
Quite Simple, so there can be two approaches for finding Sum of N Natural Numbers, let’s implement both of these and write Python Code for finding sum of n Natural Numbers.

## 1) Python Code for Finding Sum of N Natural Numbers

``````# Sum of natural numbers up to n num
n = 10
# Checks if number is negative
if n < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(n > 0):
sum += n
n -= 1
print("The sum is => ", sum)``````

Output

``The sum is =>  55``

Similarly, if you want to ask your user about How many Natural Numbers sum to find? then instead of having n = 10 on line 2 with n = input(‘Enter A Number’).

## 2) Short Way for Finding Sum of N Natural Numbers Using Python

``````# Sum of natural numbers up to n num
user_input = input("Enter a Number => ")

# Converting to int as input() by default is a string
n = int(user_input)

# Checks if number is negative
if n < 0:
print("Enter a positive number")
else:
sum = n * (n + 1)/2
print("The sum is => ", sum)``````

When running the above code, a prompt will be shown to user Enter a Number => after user enters number then code will be executed. If user entered non-negative then above code will show “Enter a positive number” otherwise code will execute and return sum of N Natural Numbers.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io