Simple use if statement with a while loop to calculate the Sum of n numbers in Python. Taken a number input from the user and stored it in a variable num.
Use a while loop to iterate until num gets zero. In every iteration, add the num to the sum, and the value of the num is decreased by 1.
Example sum of n numbers using while loop in Python
Simple example code sum of natural numbers up to num.
num = 15
sum = 0
# use while loop to iterate until zero
while num > 0:
sum += num
num -= 1
print("The sum is", sum)
Output:
User input number sum
sum = 0
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 sum is", sum)
Output:
Enter a number: 10
The sum is 55
Do comment if you have any doubts or suggestions on this Python sum topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.