How do you find the sum of n natural numbers in python?

In the program below, we've used an if...else statement in combination with a while loop to calculate the sum of natural numbers up to num.

Source Code

# Sum of natural numbers up to num

num = 16

if num < 0:
   print["Enter a positive number"]
else:
   sum = 0
   # use while loop to iterate until zero
   while[num > 0]:
       sum += num
       num -= 1
   print["The sum is", sum]

Output

The sum is 136

Note: To test the program for a different number, change the value of num.

Initially, the sum is initialized to 0. And, the number is stored in variable num.

Then, we used the while loop to iterate until num becomes zero. In each iteration of the loop, we have added the num to sum and the value of num is decreased by 1.

We could have solved the above problem without using a loop by using the following formula.

n*[n+1]/2

For example, if n = 16, the sum would be [16*17]/2 = 136.

Your turn: Modify the above program to find the sum of natural numbers using the formula below.

Python Program to Find the Sum of Natural Numbers

Natural numbers:

As the name specifies, a natural number is the number that occurs commonly and obviously in the nature. It is a whole, non-negative number.

Some mathematicians think that a natural number must contain 0 and some don't believe this theory. So, a list of natural number can be defined as:

See this example:

This example shows the sum of the first 100 positive numbers [0-100]

Output:

For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to [email protected]

Help Others, Please Share

In this tutorial, we will write a simple Python program to calculate the sum of first n natural numbers.

Program to calculate sum of first n natural numbers in Python

In this program we are not using the natural number addition formula n[n+1]/2, instead we are adding the natural numbers using while loop. The user is asked to enter the value of n and then the program calculates the sum of natural numbers upto the entered value n.

# Program published on //beginnersbook.com

# Python program to calculate the sum of n Natural Numbers

# n denotes upto which number you want to calculate the sum
# for example, if n is 5 then the sum of first 5 natural numbers
num = int[input["Enter the value of n: "]]
hold = num
sum = 0

if num  0:
        sum = sum + num
        num = num - 1;
    # displaying output
    print["Sum of first", hold, "natural numbers is: ", sum]

Output 1:

Enter the value of n: 6
Sum of first 6 natural numbers is:  21

Output 2:

Enter the value of n: 0
Enter a whole positive number!

Output 3:

Enter the value of n: -10
Enter a whole positive number!

Output 4:

Enter the value of n: 20
Sum of first 20 natural numbers is:  210

Related Python Examples:

1. Python program to add digits of a number
2. Python program to add subtract multiply and divide two numbers
3. Python program to add two matrices
4. Python program to add two binary numbers

Find the Sum of The First N Natural Numbers in Python

Given an integer input the objective is to write a code to Find the Sum of First N Natural Numbers in C++. To do so we simply keep adding the value of the iter variable using a for loop.

Example
Input : num = 8
Output : 36 Where first 8 number is 1, 2, 3, 4, 5, 6, 7, 8 Sum of numbers = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36

Find the Sum of the First N Natural Numbers in Python

Given an integer input of N, the objective is to find the sum of all the natural numbers until the given input integer. To do so we can use different approaches to write the Python code and some such methods are mentioned below,

  • Method 1 : Using for Loop
  • Method 2 : Using Formula for the Sum of Nth Term
  • Method 3 : Using Recursion

We’ll discuss and learn more about each above mentioned method in detail in the sections below.

Method 1 : Using for Loop

In this method we’ll add all the natural numbers until the given integer input using for loop in Python.

Python Code

num = 5
sum = 0
for i in range[num+1]:
  sum+=i
print[sum]

Output

Working

For a user input num.

  1.  Initialize a variable sum = 0.
  2. Using a for loop in iteration ‘i’ iterate between [1, num].
  3. Each time add ‘i’ to current sum as sum = sum + i.
  4. Print sum.

Explanation

Given an integer input N, the objective is to calculate the sum of all the natural numbers until the integer N. To do so we iterate through all the numbers that lay within N and keep incrementing the sum value.

The algorithm for the above code is as follows,

  1.  Import the required module using the import keyword.
  2. Initialize the required variables.
  3. Run a for loop with range as N+1.
  4. Keep adding the iter values to the Sum variable.
  5. Print Sum variable using print[] function.

The output for the above mentioned code is the sum of all the natural numbers until the given value.

Method 2 : Using Formula for the Sum of Nth Term

In this Method we use the formula for finding the sum of N term.

Formula to Find the Sum of N terms Sum = [ Num * [ Num + 1 ] ] / 2

Python Code

num = 5
print[int[num*[num+1]/2]]

Output

Working

For a user input n.

  1. Initialize a variable sum = 0.
  2. Use formula sum = n[n+1]/2.
  3. Print sum

Explanation

Given an integer input N, the objective is to calculate the sum of all the natural numbers until the integer N. To do so we iterate through all the numbers that lay within N and keep incrementing the sum value.

The algorithm for the above code is as follows,

  1.  Import the required modules using the import keyword.
  2. Initialize the required variables.
  3. Run a for loop with range as N+1.
  4. Keep adding the iter values to the Sum variable.
  5. Print Sum variable using print[] function.

This algorithm uses the formula n[n+1]/2 that can be used to find sum of first N natural numbers. This also reduces the time complexity from O[n] to O[1]. The output for the above mentioned code is the sum of all the natural numbers until the given value.

Method 3 : Using Recursion

This method uses Recursion to recursively add the natural numbers up to the given integer input using recursion in c++.

Python Code

def getSum[num]:
  if num == 1:
    return 1
  return num + getSum[num-1]

num = 5
print[getSum[num]]

Output

Working

For a user input n.

  1. Initialize a variable sum = 0.
  2. Call function getSum [num].
  3. In each recursive call add the current value of n and call for lower recursion call using return num + getSum[num-1];
  4. Print sum value

Explanation

Given an integer input N, the objective is to calculate the sum of all the natural numbers until the integer N. To do so we recursively call a function  iterate through all the numbers that lay within N and keep incrementing the sum value.

The algorithm for the above code is as follows,

  1.  Import the required modules using the import keyword.
  2. Define a Recursive function getSum[] which takes the number input as an argument.
  3. Recursively call the function and keep on adding the return statements.
  4. Initialize the required variables.
  5. Call the Recursive function and print out the returned value using cout keyword.

The output for the above mentioned code is the sum of all the natural numbers until the given value.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 150+ courses offered by PrepInsta in One Subscription

Get over 150+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA [All Languages], Competitive Coding [All Languages], TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Getting Started

  • ASCII Table
  • Positive or Negative number: C | C++ |  Java | Python
  • Even or Odd number: C | C++ | Java | Python
  • Sum of First N Natural numbers:  C | C++ | Java | Python
  • Sum of N natural numbers:  C | C++ | Java | Python
  • Sum of numbers in a given range: C | C++ | Java  | Python
  • Greatest of two numbers: C | C++ | Java | Python
  • Greatest of the Three numbers: C | C++ | Java | Python
  • Leap year or not: C | C++ | Java | Python
  • Prime number: C | C++ | Java | Python
  • Prime number within a given range: C | C++ | Java | Python
  • Sum of digits of a number: C | C++ | Java | Python
  • Reverse of a number : C | C++ | Java | Python
  • Palindrome number: C | C++ | Java | Python
  • Armstrong number : C | C++ | Java | Python
  • Armstrong number in a given range : C | C++ | Java | Python
  • Fibonacci Series upto nth term : C | C++ | Java | Python
  • Find the Nth Term of the Fibonacci Series : C | C++ | Java | Python
  • Factorial of a number : C | C++ | Java | Python
  • Power of a number : C | C++ | Java | Python
  • Factor of a number : C | C++ | Java | Python
  • Finding Prime Factors of a number : C | C++ | Java | Python
  • Strong number : C | C++ | Java | Python
  • Perfect number : C | C++ | Java | Python
  • Automorphic number : C | C++ | Java | Python
  • Harshad number : C | C++ | Java | Python
  • Abundant number : C| C++ | Java | Python
  • Friendly pair : C | C++ |   Java | Python

How do you write the sum of n natural numbers in Python?

See this example:.
num = int[input["Enter a number: "]].
if num < 0:.
print["Enter a positive number"].
sum = 0..
# use while loop to iterate un till zero..
while[num > 0]:.
sum += num..

How do you find the sum of n in Python?

Python program to find sum of n numbers using for loop Here, we can take an initial value sum = 0. The for loop is used for iteration number + 1 is used to increase the number up to the given input. The sum = sum + value is used to find the sum. To get the output, I have used print[sum].

How do you find the sum of n natural numbers?

The formula of the sum of first n natural numbers is S=n[n+1]2 .

How do you find the sum of natural numbers in a Python loop?

First, we have taken an int data type number input from the user and stored it in a variable num..
Read the input [num] from the user..
Initialize a variable sum with zero..
Use a for loop to iterate from 1 to num..
Inside the loop, add the num to the sum..
At the end, print the value of the sum..

Chủ Đề