In this program we will see how to accomplish the basic calculator functionalities of a calculator using a python program. Here we create individual functions to carry out the calculations and return the result. Also user input is accepted along with the choice of operator.
Example
# This function performs additiion def add(a, b): return a + b # This function performs subtraction def subtract(a, b): return a - b # This function performs multiplication def multiply(a, b): return a * b # This function performs division def divide(a, b): return a / b print("Select an operation.") print("+") print("-") print("*") print("/") # User input choice = input("Enter operator to use:") A = int(input("Enter first number: ")) B = int(input("Enter second number: ")) if choice == '+': print(A,"+",B,"=", add(A,B)) elif choice == '-': print(A,"-",B,"=", subtract(A,B)) elif choice == '*': print(A,"*",B,"=", multiply(A,B)) elif choice == '/': print(A,"/",B,"=", divide(A,B)) else: print("Invalid input")
Output
Running the above code gives us the following result −
Select an operation. + - * / Enter operator to use: - Enter first number: 34 Enter second number: 20 34 - 20 = 14