Basic Calculator

Implement a calculator that performs basic arithmetic operations (+, -, *, /). Use exception handling to deal with scenarios like division by zero and non-numeric inputs.

Example 1:

Input: num1 = "10", num2 = "2", operation = "/" 
Output: 5.0

Example 2:

Input: num1 = "10", num2 = "0", operation = "/" 
Output: "Error: Division by zero is undefined."

Convert the inputs to floats using the built-in float() function, then perform the operations. Be sure to wrap the operation in a try/except block to handle potential exceptions.

def basic_calculator(num1, num2, operation):
    try:
        num1, num2 = float(num1), float(num2)
        if operation == '+':
            return num1 + num2
        elif operation == '-':
            return num1 - num2
        elif operation == '*':
            return num1 * num2
        elif operation == '/':
            return num1 / num2
        else:
            return "Error: Invalid operation."
    except ValueError:
        return "Error: Invalid number input."
    except ZeroDivisionError:
        return "Error: Division by zero is undefined."

print(basic_calculator("10", "2", "/"))
print(basic_calculator("10", "0", "/"))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!