Write a Python program that takes two numbers as input from the user and outputs their sum.
Input-Output Examples
Example 1:
- Input:
Enter first number: 5
Enter second number: 10 - Output:
The sum of 5 and 10 is: 15
Example 2:
- Input:
Enter first number: -4
Enter second number: 9 - Output:
The sum of -4 and 9 is: 5
Algorithm to add two numbers
- Start
- Take input: Prompt the user to enter the first number (
num1
). - Take input: Prompt the user to enter the second number (
num2
). - Add the numbers: Compute the sum of
num1
andnum2
and store the result in the variablesum
. - Display the result: Print the value of
sum
. - End
Python Program to add two numbers
python
# Python program to add two numbers
# Take input from the user for the first number
num1 = int(input("Enter the first number: "))
# Take input from the user for the second number
num2 = int(input("Enter the second number: "))
# Add the two numbers
sum = num1 + num2
# Display the result
print(f"The sum of {num1} and {num2} is: {sum}")
Code Explanation
- Taking input from the user:
Theinput()
function is used to take input from the user. Sinceinput()
returns data as a string, we convert it to an integer using theint()
function so that mathematical operations can be performed. In the above code,num1
andnum2
store the two numbers provided by the user. - Adding the numbers:
Once we have the two numbers, the+
operator is used to add them. The result is stored in the variablesum
. - Displaying the output:
Theprint()
function is used to display the result. We use an f-string to format the output in a user-friendly way, showing both the input numbers and their sum in the output.