close
close
calculator in python using match case

calculator in python using match case

2 min read 07-12-2024
calculator in python using match case

Building a Python Calculator with match-case

Python's match-case statement (introduced in Python 3.10) provides a powerful and elegant way to handle conditional logic. This article demonstrates how to leverage match-case to create a flexible and readable calculator. We'll build a calculator that can handle basic arithmetic operations (+, -, *, /) and provide user-friendly error handling.

Understanding match-case

Before diving into the calculator, let's briefly review the match-case syntax. It allows us to match a subject expression against multiple patterns. If a pattern matches, the corresponding code block is executed.

match expression:
    case pattern1:
        # Code block 1
    case pattern2:
        # Code block 2
    case _:  # Default case (optional)
        # Code block for unmatched expressions

Building the Calculator

Our calculator will take two numbers and an operator as input from the user. The match-case statement will determine the appropriate operation to perform.

def calculator():
    """Performs basic arithmetic operations using match-case."""
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        operator = input("Enter the operator (+, -, *, /): ")

        match operator:
            case "+":
                result = num1 + num2
                print(f"Result: {num1} + {num2} = {result}")
            case "-":
                result = num1 - num2
                print(f"Result: {num1} - {num2} = {result}")
            case "*":
                result = num1 * num2
                print(f"Result: {num1} * {num2} = {result}")
            case "/":
                if num2 == 0:
                    print("Error: Division by zero!")
                else:
                    result = num1 / num2
                    print(f"Result: {num1} / {num2} = {result}")
            case _:
                print("Invalid operator!")

    except ValueError:
        print("Invalid input. Please enter numbers only.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


if __name__ == "__main__":
    calculator()

This code first prompts the user for two numbers and an operator. The try-except block handles potential ValueError exceptions (if the user enters non-numeric input) and other unexpected errors. The match-case statement then elegantly handles the different arithmetic operations. Notice the specific handling of division by zero. The default case (case _) catches invalid operator inputs.

Extending the Calculator

This is a basic example. We can easily extend this calculator to include more advanced features:

  • More Operators: Add support for modulo (%), exponentiation (**), etc.
  • Input Validation: Implement more robust input validation to handle various edge cases.
  • Functions: Incorporate more complex mathematical functions (e.g., square root, sine, cosine).
  • GUI: Create a graphical user interface (GUI) using libraries like Tkinter or PyQt for a more user-friendly experience.

Conclusion

The match-case statement provides a concise and readable way to implement a calculator in Python. Its pattern-matching capabilities make it easy to handle different operations and error conditions. This example demonstrates a fundamental application, offering a solid foundation for building more sophisticated calculators with added features and functionalities. The clear structure and error handling improve the overall robustness and usability of the code.

Related Posts


Popular Posts