Table of Contents

Python Function to Add Two Numbers

Example Description
Learn how to write a Python function that accepts two numbers, calculates their sum, and displays the result.

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:

  1. Define the function addnum() to add two numbers.
  2. Inside the addnum() function:
    1. Prompt the user to enter the first number and store it in the variable fnum.
    2. Prompt the user to enter the second number and store it in the variable snum.
    3. Calculate the sum of fnum and snum and store it in the variable sum.
    4. Display the sum with a message showing the values of fnum, snum, and the result sum.
  3. 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