How do you sum a number in a while loop in python?

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.

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.

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Sum of N numbers using a while loop in Python #

To get the sum of N numbers using a while loop:

  1. Iterate for as long as the number is greater than 0.
  2. On each iteration, decrement the number by 1.
  3. On each iteration, increment the total by the number.

Copied!

sum_of_numbers = 0 num = 5 while num > 0: # 👇️ reassign sum to sum + num sum_of_numbers += num # 👇️ reassign num to num - 1 num -= 1 print[sum_of_numbers] # 👉️ 15 [5 + 4 + 3 + 2 + 1] print[num] # 👉️ 0

The while loop in the example iterates for as long as the num variable stores a value greater than 0.

On each iteration, we use the += operator to reassign the sum_of_numbers variable to its current value plus num.

To move towards the base case, we also use the -= operator to reassign the num variable to its value minus 1.

The following 2 lines of code achieve the same result:

  • sum_of_numbers += num
  • sum_of_numbers = sum_of_numbers + num

Similarly, the -= operator is also a shorthand:

  • num -= 1
  • num = num - 1

Make sure to specify a base case that has to be met to exit the while loop, otherwise you might end up with an infinite loop.

A commonly used alternative is to use a while True loop with a break statement.

Copied!

sum_of_numbers = 0 num = 5 while True: # 👇️ reassign sum to sum + num sum_of_numbers += num # 👇️ reassign num to num - 1 num -= 1 # 👇️ if num is equal to or less than `0`, break out of loop if num

Chủ Đề