Sum of n numbers in Python using while loop
In this post, you will learn how to find the sum of n natural numbers using a while loop in Python programming language. The while loop in Python is used to iterate over a block of code as long as the truth expression (condition) is true.
In the given example, we have used the if..else statement in combination with a while loop to calculate the sum of n numbers. First, we have taken a number input from the user and stored it in a variable num. Initially, the sum is initialized to 0. The while loop is then used to iterate until the num equals zero. In every iteration of the loop, we have added the num to the sum, and the value of the num is decreased by 1.
# Sum of natural numbers up to num
num = int(input("Enter a number: "))
if num < 0:
print("Please enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The result is", sum)
Output1 of the above code:
Enter a number: 15
The result is 120
The above example shows the sum of the first 15 positive numbers (0-15).
Output2 of the above code:
Enter a number: 22
The result is 253
Related Articles
Print first 10 natural numbers using while loopFind square of a number in Python
Generate random numbers in Python
Sum of even numbers in Python
Swapping of two numbers in Python
Find average of n numbers in Python
Python program to print all even numbers between 1 to 100
Sum of n numbers in Python using while loop
Python program to list even and odd numbers of a list
Python program to print odd numbers within a given range
Python program to multiply two numbers
Program to find area of triangle in Python
Find area of rectangle in Python
Swapping of two numbers in Python
Find average of n numbers in Python
Print multiplication table in Python
Python program to multiply two matrices
Python program to find area of circle
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Count consonants in a string Python
Convert array to list Python