In this blog, we will discuss and solve how to write a python program to add two numbers. The resultant sum is displayed on the screen. Add two numbers often seems to be too easy. We will discuss how to find the sum or addition of two numbers in python. We have also discussed different ways through which users can provide input, and much more.
Algorithm for Python Program to Add Two Numbers:
- Declare two variables.
- Initialize the variables with some values.
- Declare another variable to store the sum of the numbers.
- Apply the mathematical plus(+) operator between two values and store the result.
Method 1: Standard program to add two numbers in python
a = 25 b = 25 sum = a + b print("The sum of two numbers is:", sum)
Output: The sum of two numbers is: 50
This is a straightforward approach to finding the sum of two numbers. Let’s have a look at how to find the sum of two numbers in python using the method.
Method 2: Addition of two numbers in python By using the user-defined method:
python allows the user to read the input. We will use the sum function to add to numbers but here is one trick to use it i.e. insert the numbers in the list, and then pass the list in the sum method. Sum method will give you the result by adding the two numbers.
Below is the implementation of the program.
Code to add two numbers in python using user defined method:
x = int(input("Enter First Number:\n")) y = int(input("Enter Second Number:\n")) Sum = sum([x,y]) print("Sum of", x, "and", y, "is", Sum)
Output Enter First Number: 12 Enter Second Number: 32 Sum of 12 and 32 is 44
Method 3: Addition of two numbers in python By using Mathematical method:
We can add two numbers by using simple mathematical tricks. We know that :-
Code to add two numbers in python using mathematical method
x = int(input("Enter First Number:\n")) y = int(input("Enter Second Number:\n")) q1 = x*x-y*y q2 = x-y Sum = q1//q2 print("Sum of", x, "and", y, "is", Sum)
Output: Enter First Number: 20 Enter Second Number: 10 Sum of 20 and 10 is 30
In this article, we have studied how to write a python program to add two numbers using different methods. Along with that we have also learned how to take input from user. We hope this blog has helped you to enhance your knowledge regarding the python programming language.
Other Python Programs
Python program to reverse a number
Python program for heap sort
Python program to check armstrong number
Python program to check leap year
Python program to convert celsius to fahrenheit
Python program to find factorial of a number
Python program to find the middle of a linked list using only one traversal
Python program to reverse a linked list