Python program to take two numbers from user input and print their sum with test cases 2025
This refined query specifies the programming language (Python), clarifies the task (taking two numbers from user input and printing their sum), and includes 'test cases' to target resources that validate the solution, while also indicating the current year for relevance.
To create a Python program that takes two numbers from the user and prints their sum, we will leverage the built-in input() function to capture user input, convert that input into integers (or floats, based on your requirement), and then compute the sum. Below is a complete program along with example test cases to ensure functionality.
# Function to add two numbers
def add_two_numbers(num1, num2):
return num1 + num2
# Main function to execute the program
def main():
try:
# Taking input from the user
number1 = float(input("Enter the first number: ")) # Using float for broader number types
number2 = float(input("Enter the second number: "))
# Calculating the sum
result = add_two_numbers(number1, number2)
# Printing the sum
print(f"The sum of {number1} and {number2} is: {result}")
except ValueError:
print("Please enter valid numbers.")
# Calling the main function
if __name__ == "__main__":
main()
Function Definition:
add_two_numbers(num1, num2) takes two parameters and returns their sum.User Input:
main() function prompts the user to enter two numbers. We use float(input()) to ensure that both integer and decimal inputs are valid.Error Handling:
ValueError exceptions, which might occur if the user enters non-numeric values.Output:
To validate the functionality of the program, you can run the following test cases:
Test Case 1:
3 and 5The sum of 3.0 and 5.0 is: 8.0Test Case 2:
-2.5 and 1.5The sum of -2.5 and 1.5 is: -1.0Test Case 3:
0 and 0The sum of 0.0 and 0.0 is: 0.0Test Case 4 (invalid input):
abc and 2Please enter valid numbers.This program efficiently captures user input, performs a basic arithmetic operation, and handles errors gracefully. By running the suggested test cases, you can confirm that the program behaves as expected under various scenarios. Feel free to modify the prompt messages or the data types as per your specific requirements.