Generation

generate functionFri, 03 Jan 2025

Create a calculator

**Calculator in Python** ========================= Below is a simple implementation of a calculator in Python that performs basic arithmetic operations. ```python # Calculator in Python class Calculator: def __init__(self): pass def add(self, num1, num2): """Returns the sum of two numbers.""" return num1 + num2 def subtract(self, num1, num2): """Returns the difference of two numbers.""" return num1 - num2 def multiply(self, num1, num2): """Returns the product of two numbers.""" return num1 * num2 def divide(self, num1, num2): """Returns the quotient of two numbers.""" if num2 == 0: raise ValueError("Cannot divide by zero.") return num1 / num2 def calculate(self): """Performs a calculation based on user input.""" print("Select an operation:") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice = input("Enter your choice (1/2/3/4): ") if choice in ('1', '2', '3', '4'): num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) if choice == '1': print(f"{num1} + {num2} = {self.add(num1, num2)}") elif choice == '2': print(f"{num1} - {num2} = {self.subtract(num1, num2)}") elif choice == '3': print(f"{num1} * {num2} = {self.multiply(num1, num2)}") elif choice == '4': try: print(f"{num1} / {num2} = {self.divide(num1, num2)}") except ValueError as e: print(str(e)) else: print("Invalid choice.") def main(): calculator = Calculator() while True: calculator.calculate() cont = input("Do you want to continue? (yes/no): ") if cont.lower() != 'yes': break if __name__ == "__main__": main() ``` **How to Use:** 1. Run the script. 2. Select an operation by entering the corresponding number (1 for addition, 2 for subtraction, 3 for multiplication, 4 for division). 3. Enter the two numbers. 4. The calculator will display the result. 5. To continue, enter "yes" when prompted. To exit, enter "no". **Note:** This is a basic implementation and does not handle more complex calculations or edge cases. You can extend this code to add more features as needed.

Want to kickstart your project?Use the new AI Studio to create your code