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 sum, and the value of 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)
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)
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 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.