Python match case statement

Starting from Python 3.10, a new feature called “match” and “case” has been introduced in Python. The “match” statement allows you to perform pattern matching on values, similar to a switch statement in other programming languages.

Here’s an example program that demonstrates the usage of “match” and “case” in Python:

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

    match operator:
        case '+':
            result = num1 + num2
            print(f"The sum of {num1} and {num2} is: {result}")
        case '-':
            result = num1 - num2
            print(f"The difference between {num1} and {num2} is: {result}")
        case '*':
            result = num1 * num2
            print(f"The product of {num1} and {num2} is: {result}")
        case '/':
            if num2 != 0:
                result = num1 / num2
                print(f"The division of {num1} by {num2} is: {result}")
            else:
                print("Error: Division by zero is not allowed.")
        case _:
            print("Invalid operator.")

# Example usage
calculator()

Sample Output :

Enter the operator (+, -, *, /): +
Enter the first number: 23
Enter the second number: 32
The sum of 23.0 and 32.0 is: 55.0
Information shared by : THYAGU

7 thoughts on “Python match case statement

  1. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  2. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

Leave a Reply

Your email address will not be published. Required fields are marked *