How to Create a Simple Calculator with Error Handling

100 views

How to Create a Simple Calculator with Error Handling

How to Create a Simple Calculator with Error Handling

I want to build a basic calculator that can add, subtract, multiply, and divide, but I also want to include error handling. How can I do this?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

Implementing a calculator with error handling involves capturing user input, performing the desired operations, and handling possible errors like division by zero.

Code Example:

def calculator():
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        operation = input("Enter the operation (+, -, *, /): ")

        if operation == '+':
            print(f"Result: {num1 + num2}")
        elif operation == '-':
            print(f"Result: {num1 - num2}")
        elif operation == '*':
            print(f"Result: {num1 * num2}")
        elif operation == '/':
            if num2 == 0:
                raise ZeroDivisionError("Cannot divide by zero.")
            print(f"Result: {num1 / num2}")
        else:
            print("Invalid operation. Please enter +, -, *, or /.")
    except ValueError:
        print("Invalid input. Please enter numeric values.")
    except ZeroDivisionError as e:
        print(e)

# Example usage
calculator()

This function provides a menu-driven interface, performs the selected operation, and includes error handling for common user mistakes.

solveurit24@gmail.com Changed status to publish February 16, 2025
0