Python Program to Add Two Numbers

Adding two numbers is one of the simplest and most common tasks in programming. It is a fundamental operation that forms the basis for many complex algorithms and applications. In this article, we will explore how to write a Python program to add two numbers. This will help beginners understand basic input/output operations and arithmetic operations in Python.

Example 1:

  • Input: 3, 5
  • Output: 8

Example 2:

  • Input: -1, 4
  • Output: 3

Python Program to Add Two Numbers

In Python, we can add two numbers using the + operator. The program will take two numbers as input from the user and display their sum. Below is the implementation code with comments for better understanding.

# Function to add two numbers
def add_numbers(a, b): return a + b # Main function to get user input and display the result def main(): # Taking input from the user num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) # Adding the two numbers result = add_numbers(num1, num2) # Displaying the result print(f"The sum of {num1} and {num2} is {result}") # Calling the main function if __name__ == "__main__": main()

Output :


Explanation of the Code

1. Function Definition:

  • add_numbers(a, b): This function takes two arguments a and b returns their sum using the + operator.
2. Main Function:
  • The main() function is where the user inputs are taken the addition is performed and the result is displayed.
  • num1 and num2 are inputs taken from the user and converted to floating-point numbers using the float() function to handle decimal values.
  • The add_numbers() function is called with num1 and num2 as arguments and result is stored in the result variable.
  • The result is then printed using an f-string for formatted output.

Conclusion

This article covered the basics of adding two numbers in Python. The provided example and code implementation should help you understand how to take user input perform the addition and display the result. Understanding this fundamental operation is essential as it forms the basis for more complex programming tasks.

Post a Comment

Previous Post Next Post