Introduction:
This Python program demonstrates the use of a function to add two numbers based on user input. The program defines a function add_numbers(a, b) that takes two parameters and returns their sum. It then prompts the user to input two numbers, converts them to floating-point values, and calls the add_numbers function to calculate their sum. Finally, the program displays the result on the console.
Algorithm:
- Define a function add_numbers(a, b) that takes two parameters a and b.
- Inside the function, calculate and return the sum of a and b using the +
- Prompt the user to enter the first number and store it in the variable num1.
- Prompt the user to enter the second number and store it in the variable num2.
- Convert both num1 and num2 to floating-point values using float().
- Call the add_numbers function with num1 and num2 as arguments and store the result in the variable result.
- Display the result with a descriptive message, e.g., “Sum: <result>”.
Python Code:
def add_numbers(a, b):
return a + b
# Get user input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Call the function and display the result
result = add_numbers(num1, num2)
print("Sum:", result)
Input :
Enter the first number: 5
Enter the second number: 6
Output :
Sum: 11.0
Explanation:
- The program begins by defining the add_numbers function, which accepts two parameters a and b, and returns their sum using the + operator.
- The program then prompts the user to input the first and second numbers, which are stored in the variables num1 and num2 respectively.
- The float() function is used to convert the user input to floating-point numbers, allowing decimal values to be entered.
- The add_numbers function is called with num1 and num2 as arguments, and the result is stored in the variable result.
- Finally, the program displays the sum of the two numbers by printing “Sum: “ followed by the value of the result variable.
This program showcases the use of a simple function to perform a specific task (addition) and demonstrates how user input can be obtained, processed, and utilized to perform calculations.