Write a Python program to define a class Calculator

Write a Python program to define a class Calculator

Write a Python program to define a class Calculator with a method calculate() that behaves differently based on the number of arguments passed: If one argument is passed, return its square. If two arguments are passed, return their sum. If three or more arguments are passed, return “Invalid number of arguments”.

class Calculator:
    # Using *args to handle variable number of arguments
    def calculate(self, *args):
        """
        Performs different operations based on the number of arguments.
        - 1 arg: returns square of the number.
        - 2 args: returns sum of the two numbers.
        - 3+ args: returns an error message.
        """
        num_args = len(args)

        if num_args == 1:
            # Square the single argument
            return args[0] ** 2
        elif num_args == 2:
            # Sum of two arguments
            return args[0] + args[1]
        else:
            # Invalid number of arguments
            return "Invalid number of arguments"

# --- Creating an object and testing the calculate method ---
calc = Calculator()

print("--- Testing the Calculator ---")
# Test case 1: One argument (e.g., 7)
print(f"calculate(7) -> {calc.calculate(7)}")

# Test case 2: Two arguments (e.g., 15 and 25)
print(f"calculate(15, 25) -> {calc.calculate(15, 25)}")

# Test case 3: Three arguments (e.g., 1, 2, 3)
print(f"calculate(1, 2, 3) -> {calc.calculate(1, 2, 3)}")

# Test case 4: Four arguments
print(f"calculate(10, 20, 30, 40) -> {calc.calculate(10, 20, 30, 40)}")