Back to Data Structures & Algorithms
2026-03-155 min read

Algorithm 1: Add two numbers entered by the user (Data Structures & Algorithms)

Learn Algorithm 1: Add two numbers entered by the user (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

Learning to write algorithms is crucial in computer science as it helps us understand how computers process data. In this lesson, we will focus on a simple yet essential algorithm: adding two numbers entered by the user. This algorithm serves as a stepping stone towards more complex data structures and algorithms. It's important for exams, interviews, and real-world programming scenarios where you may need to manipulate user input.

Prerequisites

Before diving into this lesson, make sure you have a basic understanding of the following:

  1. Python syntax and variables
  2. User input in Python using input() function
  3. Basic arithmetic operations in Python (addition, subtraction, multiplication, division)
  4. Data types in Python (int, float, string) and their properties
  5. If-else statements for conditional execution
  6. Error handling using try-except blocks
  7. Understanding the difference between integer and floating-point numbers, and when to use each type
  8. Basic concepts of data validation and input sanitization
  9. How to check if a string is numeric using isnumeric() function

Core Concept

The core concept of this algorithm is to take two numbers as user input, perform addition, handle potential errors, and display the result. Let's break it down step-by-step:

  1. Request user input for the first number using input() function.
  2. Convert the user input into a variable (e.g., num1) of appropriate data type (usually an integer or float). Use isnumeric() to check if the input is numeric before converting it. If the conversion fails, ask for valid input again.
  3. Request user input for the second number using input() function once more. Perform the same validation and error handling as before.
  4. Perform addition on the two variables, ensuring that both numbers are of the same data type to avoid unexpected results due to type coercion. Store the result in a third variable (e.g., result).
  5. Print the result using the print() function.

Here's an example code snippet that demonstrates this algorithm with error handling:

def get_number(prompt):
while True:
num = input(prompt)
if num.isnumeric():
return float(num)
else:
print("Invalid input. Please enter a valid number.")

num1 = get_number("Enter the first number (integer or float): ")
num2 = get_number("Enter the second number (same data type as the first): ")

if isinstance(num1, int) and isinstance(num2, int):
result = num1 + num2
elif isinstance(num1, float) and isinstance(num2, float):
result = num1 + num2
else:
print("Error: The two numbers must be of the same data type.")
return

print("The sum of the two numbers is:", result)

Worked Example

Let's walk through an example to better understand how this algorithm works with error handling. Suppose we want to add 5 and 3, but the user enters invalid input:

  1. The user enters abc when prompted for the first number. This value will not be numeric, so the function get_number() will ask for input again.
  2. After entering valid input (e.g., 5), the user enters 3 when prompted for the second number.
  3. Since both numbers are integers, we perform addition on num1 and num2, storing the result in result.
  4. Finally, we print the result, which is 8.

Common Mistakes

  1. Forgetting to handle invalid user input gracefully. If you forget to include error handling for non-numeric characters or empty inputs, your program will crash. It's essential to use functions like get_number() to handle these cases and provide a better user experience.
  1. Not checking if the user input is numeric before performing arithmetic operations. This can lead to errors and unexpected behavior if non-numeric characters are present in the input.
  1. Incorrect data type conversion. Using the wrong function (e.g., int() instead of float()) can lead to rounding errors or truncation, causing the result to be different from what you expect.
  1. Not ensuring that both numbers are of the same data type before performing addition. This can cause unexpected results due to type coercion, which may not always produce the desired outcome.

Practice Questions

  1. Write a Python program that takes two numbers as input, calculates their product, and displays the result with error handling for invalid user input.
  1. Modify the given example code to handle cases where the user enters an empty string instead of a number by displaying an appropriate error message and asking for input again.
  1. Write a Python program that takes three numbers as input (two for addition and one for subtraction), handles potential errors, and displays the result of the operation.
  1. Modify the given example code to include multiplication instead of addition. The user should be able to choose whether they want to add or multiply the two numbers by prompting them before performing the operation.
  1. Write a Python program that takes a list of numbers as input, calculates their sum, and displays the result with error handling for invalid user input. Ensure that the program can handle both integers and floats in the list.

FAQ

Why do we need to check if the user input is numeric before converting it?

Checking if the user input is numeric helps prevent errors and unexpected behavior when performing arithmetic operations. Non-numeric characters can cause issues like TypeError or ValueError, which may crash your program or produce incorrect results.

Why do we need to ensure that both numbers are of the same data type before performing addition?

Ensuring that both numbers are of the same data type helps prevent unexpected results due to type coercion. For example, if you add an integer and a float, Python will automatically convert the integer to a float, which may not always produce the desired outcome. By ensuring that both numbers are of the same data type, we can avoid these issues and get accurate results.

What should I do if my program crashes due to user input errors?

If your program crashes due to user input errors, you should add error handling functions like get_number() to gracefully handle invalid inputs and provide a better user experience. This will help prevent crashes and make your program more robust.

Algorithm 1: Add two numbers entered by the user (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn