Introduction:
This Python code demonstrates how to create a function that accepts two numbers from the user, calculates their sum, and displays the result.
Code:
#Function to add two numbers
#The requirements are listed below:
#1. We need to accept 2 numbers from the user.
#2. Calculate their sum
#3. Display the sum.
#function definition
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
sum = fnum + snum
print("The sum of ",fnum,"and ",snum,"is ",sum)
#function call
addnum()
Logic:
- Define the function
addnum()
to add two numbers. - Inside the
addnum()
function:- Prompt the user to enter the first number and store it in the variable
fnum
. - Prompt the user to enter the second number and store it in the variable
snum
. - Calculate the sum of
fnum
andsnum
and store it in the variablesum
. - Display the sum with a message showing the values of
fnum
,snum
, and the resultsum
.
- Prompt the user to enter the first number and store it in the variable
- Call the
addnum()
function, which will execute the above steps when the code is run.
Output:
The sum of [first number] and [second number] is [sum]
Enter first number: 10
Enter second number: 5
>> The sum of 10 and 5 is 15