Python Program to Find the Sum of Natural Numbers Using While Loop
Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop.
Calculate Sum of Natural Numbers in Python Using While Loop
Below are some of the examples by which we can see how we can calculate the sum of N numbers in Python:
Example 1: Calculate the Sum of N Numbers Using While Loop
In this example, a Python function sum_of_natural_numbers
is defined to calculate the sum of the first N natural numbers using a while loop. The function initializes variables total
and count
, iterates through the numbers from 1 to N, and accumulates the sum in the total
variable. The result is then printed, demonstrating the sum of the first 7 natural numbers.
def sum_of_natural_numbers(N):
total = 0
count = 1
while count <= N:
total += count
count += 1
return total
N = 7
result = sum_of_natural_numbers(N)
print("The Sum of the First", N, "Natural Numbers is:",
result)
Output
The Sum of the First 7 Natural Numbers is: 28
Example 2: Calculate the Sum of N Numbers Using While Loop and User Input
In this example, the user inputs a value N, and the program calculates the sum of the first N natural numbers using a while loop, efficiently decrementing 'count' from N to 1 and accumulating the sum in the 'total' variable. The final result is then printed.
# Takes the input of N given by the user
N = int(input("Enter the value of N: "))
# Initialize the variables 'count' and 'total'
count = N
total = 0
while count:
total += count
count -= 1
# Prints the sum of N natural numbers.
print("The sum of the first", N, "natural numbers is:", total)
Output:
Enter the value of N: 16
The sum of the first 16 natural numbers is: 136