Sum of N numbers using a while loop in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Photo from Unsplash

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.
main.py
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.

main.py
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 <= 0: break print(sum_of_numbers) # 👉️ 15 (5 + 4 + 3 + 2 + 1) print(num) # 👉️ 0

The while True loop iterates until it is interrupted by a break statement.

The loop is quite similar to the previous example, however we manually check if the num variable stores a value of less than or equal to 0 on each iteration.

Which approach you pick is a matter of personal preference. I'd go with using the while loop from the first example as I find it more intuitive and easier to read.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.