def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: raise ValueError("Cannot divide by zero!") return x / y print("Select operation.") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter choice(1/2/3/4): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': try: print(num1, "/", num2, "=", divide(num1, num2)) except ValueError as e: print(e) else: print("Invalid Input")
This program allows the user to choose an operation (add, subtract, multiply, or divide) and then enter two numbers. The program then calls the appropriate function to perform the calculation and prints the result.
In this example, the calculator is implemented using functions for each operation. The user input is taken through the
input() function, which returns a string. So we have to use
float() function to convert string to float so that it could be used for the mathematical operations.
We have also handled the error scenario if a user entered a choice as anything other than 1, 2, 3, or 4 which is not supported, and also for the divide by zero error which is not allowed in mathematical operation.
You can further enhance it to add more functionality like error handling, and validation or you could use some libraries like PyQt to create a graphical user interface for the calculator.