Back to Python
2026-01-316 min read

Example: Sum of Numbers (Python Programming)

Learn Example: Sum of Numbers (Python Programming) step by step with clear examples and exercises.

Why This Matters

In this full guide, we will delve into a fundamental aspect of Python programming: calculating the sum of numbers using loops. This skill is crucial for various programming tasks and can be invaluable in real-world scenarios such as data analysis or creating interactive applications.

The while loop is an essential tool that allows us to repeat a block of code multiple times, making it perfect for situations where we don't know the exact number of iterations beforehand. In this lesson, you will learn how to use the while loop in Python to calculate the sum of numbers, which can be applied to many other problems as well.

Prerequisites

To fully grasp the concepts presented in this lesson, you should have a basic understanding of:

  1. Python syntax and variables
  2. Basic data types like integers and floating-point numbers
  3. Understanding of the print() function for outputting results
  4. Familiarity with control flow structures such as if, elif, and else statements
  5. Knowledge of handling user input using functions like input()
  6. Comfortable with error handling using try-except blocks
  7. Basic understanding of list data structure (optional, but useful for practice questions)

If you're new to Python or need a refresher, we recommend checking out our Python Basics course first.

Core Concept

The core concept we will focus on today is using the while loop to calculate the sum of numbers in Python. Here's an outline of the steps involved:

  1. Initialize a variable for the total sum and another for the current number.
  2. Start the loop by setting a condition that continues until we have processed all numbers or reached a specific termination point.
  3. Inside the loop, read the next number from the user (or from a list of predefined numbers), add it to the total sum, and update the current number for the next iteration.
  4. After processing all numbers, print the final result—the total sum.
  5. Handle any errors that may occur during input or arithmetic operations using try-except blocks.
  6. (Optional) Use a list to store the numbers processed in the loop for further analysis or manipulation.

Worked Example

Let's write a simple program that calculates the sum of numbers entered by the user using the while loop:

total_sum = 0
current_num = None
numbers = []

print("Enter '0' to stop entering numbers:")
while True:
try:
current_num = float(input("Enter a number (or '0' to stop): "))
if current_num == 0:
break
total_sum += current_num
numbers.append(current_num)
except ValueError:
print("Invalid input. Please enter a valid number.")

print("The sum of the entered numbers is:", total_sum)
print("Numbers processed:", numbers)

In this example, we start by initializing three variables—total_sum, current_num, and an empty list called numbers. We then print a message asking the user to enter numbers until they input 0. Inside the loop, we use a try-except block to handle invalid input, read an input number, check if it's 0 (to terminate the loop), add the current number to the total sum, append the current number to the numbers list, and update the current number for the next iteration. Finally, after processing all numbers, we print the final result—the total sum of entered numbers, and the list of processed numbers.

Common Mistakes

  1. Forgetting to initialize the total_sum variable before starting the loop.
  2. Not checking if the user's input is a valid number (integer or float) before adding it to the total sum. To handle invalid input, you can use a try-except block as shown in the Worked Example section above.
  3. Not updating the current number after processing each number inside the loop.
  4. Using an infinite loop without a termination condition, causing the program to hang indefinitely.
  5. Incorrectly handling the edge case where the user enters 0 as the first number. To avoid this issue, you can check for the termination condition (i.e., current_num == 0) before adding the current number to the total sum inside the loop.
  6. Forgetting to initialize the list variable before starting the loop.
  7. Not appending the processed number to the list inside the loop, causing an empty list after processing numbers.
  8. Using a list of predefined numbers instead of user input and forgetting to update the termination condition accordingly.
  9. Printing the total sum without including the current number being processed in the loop, leading to incorrect results for large sets of data.
  10. Not handling negative numbers or mixed data types (e.g., integers and floats) appropriately when calculating the total sum.

Practice Questions

  1. Modify the example above to calculate the average of entered numbers instead of their sum.
  2. Write a program that calculates the sum of even numbers entered by the user until they input 0.
  3. Write a program that finds the largest number entered by the user and prints it along with the total sum of all entered numbers.
  4. Modify the example to handle negative numbers appropriately when calculating the total sum.
  5. Write a program that calculates the product of entered numbers instead of their sum.
  6. (Optional) Write a program that calculates the median of entered numbers using the while loop and the sorted list of processed numbers.
  7. (Challenge) Write a program that calculates the harmonic mean of entered numbers using the while loop and the total sum of reciprocals of processed numbers.
  8. (Bonus) Write a program that calculates the root mean square of entered numbers using the while loop and the square root of the total sum of squares of processed numbers.

FAQ

Q: Can I use other loops like for to calculate the sum of numbers in Python?

A: Yes, you can use the for loop as well to iterate over a list of numbers and calculate their sum. However, the while loop is more suitable when dealing with user input or dynamic number of iterations.

Q: What happens if I don't break out of an infinite loop in my program?

A: If you have an infinite loop without a termination condition, your program will continue running indefinitely until it is manually stopped (e.g., by closing the terminal or force-quitting the application). This can cause performance issues and make it difficult to debug the code.

Q: How can I handle invalid user input (like non-numeric values) in my program?

A: To handle invalid user input, you can use a try-except block as shown below:

total_sum = 0
current_num = None
numbers = []

print("Enter '0' to stop entering numbers:")
while True:
try:
current_num = float(input("Enter a number (or '0' to stop): "))
if current_num == 0:
break
total_sum += current_num
numbers.append(current_num)
except ValueError:
print("Invalid input. Please enter a valid number.")

print("The sum of the entered numbers is:", total_sum)
print("Numbers processed:", numbers)

Q: How can I handle negative numbers appropriately when calculating the total sum?

A: To handle negative numbers, you can use absolute values or add a condition to check for negativity and adjust the calculation accordingly:

total_sum = 0
current_num = None
numbers = []

print("Enter '0' to stop entering numbers:")
while True:
try:
current_num = float(input("Enter a number (or '0' to stop): "))
if current_num == 0:
break
total_sum += abs(current_num)
numbers.append(current_num)
except ValueError:
print("Invalid input. Please enter a valid number.")

print("The sum of the absolute values of entered numbers is:", total_sum)
print("Numbers processed:", numbers)

Q: How can I calculate the average of entered numbers instead of their sum?

A: To calculate the average, you can divide the total sum by the number of processed numbers:

total_sum = 0
current_num = None
numbers = []

print("Enter '0' to stop entering numbers:")
while True:
try:
current_num = float(input("Enter a number (or '0' to stop): "))
if current_num == 0:
break
total_sum += current_num
numbers.append(current_num)
except ValueError:
print("Invalid input. Please enter a valid number.")

if len(numbers) > 0:
average = total_sum / len(numbers)
print("The average of the entered numbers is:", average)
else:
print("No numbers were processed.")
Example: Sum of Numbers (Python Programming) | Python | XQA Learn