Press ESC to close

Python Program to Add Two Numbers

Photo by RealToughCandy.com

The code below is a python code to add two numbers and display the output.

# Function to add two numbers
def add_numbers(number1, number2):
    return number1 + number2
# Prompt the user to enter the first number
number1 = float(input("Enter the first number: "))
# Prompt the user to enter the second number
number2 = float(input("Enter the second number: "))
# Call the function to add the numbers
sum = add_numbers(number1, number2)
# Display the sum
print("The sum of", number1, "and", number2, "is", sum)

 

Explanation:

1. Define a function: add_numbers is a function that accepts two arguments and returns their sum.

def add_numbers(number1, number2):
    return number1 + number2

number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))

3. Call the function: Using the two input numbers, we call the add_numbers function and save the outcome in the variable total.

sum = add_numbers(number1, number2)

4. Present the outcome: Lastly, we use the print function to output the total.

print("The sum of", number1, "and", number2, "is", sum)

How to Run the Program:

  1. Save the code in a file called add_numbers.py or something similar with the.py extension.
  2. Open a terminal or command prompt.
  3. Open the directory in which the file was saved.
  1. Run the program using Python:
python add_numbers.py

You will be prompted to enter two numbers, and the program will display their sum.

Leave a Reply

Your email address will not be published. Required fields are marked *