In this post, we learn how to write a python program to add two numbers with a very simple explanation but before writing a program I will explain to you how easy it is to add two numbers in python.
As we know python is a dynamic programming language and it is very much flexible. We can easily add two numbers by using the +
operator and print it on the console using the print()
function. let’s see how.
# Addition of two integer numbers
print(3+5) # 8
print(10+21) #31
# Addition of two float numbers
print(3.5+21) # 24.5
print(2.1+3.4) # 5.5
Now let’s properly write this program by taking input from the user but before writing a program few programming concepts you have to know:
Source Code
# addition of a and b by taking input from the user
a = float(input('Enter first number : '))
b = float(input('Enter Second number : '))
# take one variable (c) and store the result of a+b.
c = a + b
print(f"sum of {a} and {b} is {c:.2f}")
Output
Enter first number : 4 Enter Second number : 5 sum of 4.0 and 5.0 is 9.00 |
Now let’s write the above program using a function
Add Two Numbers in Python Using Function
But before writing a program few programming concepts you have to know:
Source Code
def addTwo(num1,num2):
return num1+num2
a = float(input('Enter first number : '))
b = float(input('Enter Second number : '))
# calling a function
c = addTwo(a,b)
print(f"sum of {a} and {b} is {c:.2f}")
Output
Enter first number : 3.5 Enter Second number : 7.1 sum of 3.5 and 7.1 is 10.6 |
Related Post: