class Calculator: def __init__(self): self.history = []
def add(self, num1, num2): """Add two numbers""" result = num1 + num2 self.history.append(f"{num1} + {num2} = {result}") return result def subtract(self, num1, num2): """Subtract two numbers""" result = num1 - num2 self.history.append(f"{num1} - {num2} = {result}") return result def multiply(self, num1, num2): """Multiply two numbers""" result = num1 * num2 self.history.append(f"{num1} * {num2} = {result}") return result def divide(self, num1, num2): """Divide two numbers""" if num2 == 0: raise ValueError("Cannot divide by zero!") result = num1 / num2 self.history.append(f"{num1} / {num2} = {result}") return result def get_history(self): """Get the calculation history""" return self.history
while True: print("\nOptions:") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Get History") print("6. Quit") choice = input("Choose an option: ") if choice == "1": num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print(f"Result: {calculator.add(num1, num2)}") elif choice == "2": num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print(f"Result: {calculator.subtract(num1, num2)}") elif choice == "3": num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) print(f"Result: {calculator.multiply(num1, num2)}") elif choice == "4": num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) try: print(f"Result: {calculator.divide(num1, num2)}") except ValueError as e: print(e) elif choice == "5": print("\nCalculation History:") for i, history in enumerate(calculator.get_history()): print(f"{i+1}. {history}") elif choice == "6": break else: print("Invalid option. Please choose a valid option.")
class Calculator: def __init__(self): self.history = []
def main(): calculator = Calculator() if __name__ == "__main__": main()