HomeInterview QuestionsWrite a simple Python calculator function that can…

Write a simple Python calculator function that can add, subtract, multiply, and divide two numbers. Provide the complete code and show how to call it.

🟢 Easy Coding Fresher level
1Times asked
May 2026Last seen
May 2026First seen

💡 Model Answer

Here is a concise implementation:

python

def calculator(a, b, operation):
    """Perform a basic arithmetic operation.

    Parameters:
        a (float): First operand.
        b (float): Second operand.
        operation (str): One of '+', '-', '*', '/'.

    Returns:
        float: Result of the operation.
    """
    if operation == '+':
        return a + b
    elif operation == '-':
        return a - b
    elif operation == '*':
        return a * b
    elif operation == '/':
        if b == 0:
            raise ValueError("Division by zero is not allowed.")
        return a / b
    else:
        raise ValueError("Unsupported operation: %s" % operation)

# Example usage
print(calculator(10, 5, '+'))  # 15
print(calculator(10, 5, '-'))  # 5
print(calculator(10, 5, '*'))  # 50
print(calculator(10, 5, '/'))  # 2.0

The function uses a simple if‑elif chain to dispatch the operation. It raises a ValueError for unsupported operations or division by zero, making the behavior explicit. The example calls demonstrate how to use the function for each arithmetic operation.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500