In this article, we will learn about python program to add two numbers with or without user input.
Getting Started
The task is to find sum of two numbers. For example,
If numbers are 10 and 20, output will be 10 + 20 = 30.
We can do so in multiple ways –
Simple Approach
a = 10 b = 20 sum = a + b print("sum = ", sum)
Output:
sum = 30
In above program,
a + b returns sum of two numbers a and b.
When User Input is Given
a = float(input("Enter a number")) b = float(input("Enter another number")) sum = a + b print("sum of {0} and {1} is {2}" .format(a, b, sum))
Output:
Enter a number 10 Enter another number 20 sum of 10.0 and 20.0 is 30.0
In above program,
- float(input()) takes input from user and converts it into float number.
- sum = a + b adds two number and store the result in variable sum.
- Then, result is printed using print() method
Using Lambda
if __name__ == "__main__" : num1 = 15 num2 = 12 # Adding two numbers sum_twoNum = lambda num1, num2 : num1 + num2 print("sum = ", sum_twoNum(num1, num2))
Output:
sum = 27
Using Function
def findSum(a, b): return a + b print("sum = ", findSum(10, 20))
Output:
sum = 30
That’s how can write python program to add two numbers with or without user input.
Reference: Official Doc