In this Python example, we are going to see how we can do mathematical operations such as Addition, Subtraction, Multiplication & Division.
It’s fairly simple to do mathematical operations in Python, here I will show you a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#Addition add = 5 + 2 print ("Addition: %d" %add) #Subtraction sub = 5 - 2 print ("Subtraction: %d" %sub) #Multiplication mul = 5 * 2 print ("Multiplication: %d" %mul) #Division div = 5 / 2 print ("Division: %.2f" %div) |
An example output of the above Python script is:
1 2 3 4 |
Addition: 7 Subtraction: 3 Multiplication: 10 Division: 2.50 |
Now, this example Python program on how to do mathematical operations has hardcoded values, let’s write this application dynamic so we can get the input values from the user and do the math operations.
Let’s see an example Python Program to do the mathematical operation dynamically:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#Get the input from user print ("Enter Number 1:") num1 = int(input()) print ("Enter Number 2:") num2 = int(input()) #Addition add = num1 + num2 print ("Addition: %d" %add) #Subtraction sub = num1 - num2 print ("Subtraction: %d" %sub) #Multiplication mul = num1 * num2 print ("Multiplication: %d" %mul) #Division div = num1 / num2 print ("Division: %.2f" %div) |
That’s it, you have to just have to get the two numbers from the user and do the same operations as shown in the first example. Just go through the inline comments of the above program to understand it better.
And the sample output of this Python script is:
1 2 3 4 5 6 7 8 |
Enter Number 1: 7 Enter Number 2: 2 Addition: 9 Subtraction: 5 Multiplication: 14 Division: 3.50 |
Enjoy programming!