Home > Article > Backend Development > Lets make a Calculator
Before we actually make a calculator, let's first see some basic mathematical expressions...
1. Add
num1 = 2 num2 = 3 print(num1+num2) 5
2. Subtract
num1 = 7 num2 = 5 print(num1-num2) 2
3. Multiply
num1 = 5 num2 = 5 print(num1*num2) 25
4. Divide
num1 = 100 num2 = 5 print(num1/num2) 20
5. Modulus (nothing but remainder)
quotient = 5//2 remainder = 5 % 2 print(quotient , "," ,remainder) 2 , 1
6.Exponentiate (powers)
For ex; a power b in python written as a**b
num1 = 3 num2 = 3 print(num1**num2) 27
Input Datatype and Typecasting
# Addition num1 = int(input("Enter Number 1 : ")) num2 = int(input("Enter Number 2 : ")) result = num1+num2 print("Result is : ", result) Enter Number 1 : 1 Enter Number 2 : 4 Result is : 5
Here it appears as steps but I'm unable to present it.
You can just do it and see.
# to make it possible in decimals too we use float num1 = float(input("Enter Number 1 : ")) num2 = float(input("Enter Number 2 : ")) result = num1+num2 print("Result is : ", result) Enter Number 1 : 1.5 Enter Number 2 : 2.5 Result is : 4.0
Similarly, we do for other operations.
Now, with this knowledge we gonna create a simple calculator by using the following code;
print("Simple Calculator") print("Select Operation : ") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Modulus") print("6. Exponentiate") choice = input("Enter choice (1/2/3/4/5/6) : ") num1 = float(input("Enter first Number : ")) num2 = float(input("Enter second Number : ")) if choice == "1" : result = num1 + num2 print(result) elif choice == "2" : result = num1 - num2 print(result) elif choice == "3" : result = num1 * num2 print(result) elif choice == "4" : result = num1 / num2 print(result) elif choice == "5" : result = num1 % num2 print(result) elif choice == "6" : result = num1 ** num2 print(result) else : print("option not available")
So, that's what I learned under this topic.
You can use the same code above and chk whether it works for you too..
Platforms I use to try these codes :
.....
The above is the detailed content of Lets make a Calculator. For more information, please follow other related articles on the PHP Chinese website!