Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Switch case or match case?
#1
Hello,

I hate to ask again but i am trying to introduce a switch statement to get rid of if, else statements.

This is the original code and i would like to get rid of the if and elif. I have been reading a few posts about it saying that it is similar to switch case default in C#. But it was introduced as match case in recent versions of Python. Not so sure what to do with the implementation.

# Program make a simple calculator

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
   
    choice = input("Enter choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))
        
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break
    
    else:
        print("Invalid Input")
I started with this :

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")


    # take input from the user
def switch():
    choice = input("Enter choice(1/2/3/4): ")

    # check if choice is one of the four options
    
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

        case == "1":
            print(num1, "+", num2, "=", add(num1, num2))

        case == "2":
            print(num1, "-", num2, "=", subtract(num1, num2))

        case == "3":
            print(num1, "*", num2, "=", multiply(num1, num2))

        case == "4":
            print(num1, "/", num2, "=", divide(num1, num2))
        
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break
    
        else:
          print("Invalid Input")
Any inputs on this? Not sure how to implement this.

TY
Reply
#2
Are you trying to use the new structural pattern matching introduced in Python 3.10? As far as I know that is the only Python feature that uses "case" as a keyword. I have not installed 3.10 yet, but I believe the code would look like this:
while True:
    op = input(Select operation +, -, *, /: ")
    if op not in "+-*/":
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        match choice:
            case ['+']:
                print(num1, "+", num2, "=", num1 + num2)
            case ['-']:
                print(num1, "-", num2, "=", num1 - num2)
            case ['*']:
                print(num1, "*", num2, "=", num1 * num2)
            case ['/']:
                print(num1, "/", num2, "=", num1 / num2)
 
    if input("Let's do next calculation? (yes/no): ") == "no":
        break
I look forward to using this new feature. If I had to solve this problem without structured pattern matching I would probably fall back on using a dictionary.
operations = {
    "+": lambda a, b: print(f"{a} + {b} = {a+b}"),
    "-": lambda a, b: print(f"{a} - {b} = {a-b}"),
    "*": lambda a, b: print(f"{a} * {b} = {a*b}"),
    "/": lambda a, b: print(f"{a} / {b} = {a/b}"),
}

while True:
    op = input(f"Select operation {', '.join(operations.keys())}: ")
    if op not in operations:
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        operations[op](num1, num2)

    if input("Let's do next calculation? (yes/no): ") == "no":
        break
menator01 and Frankduc like this post
Reply
#3
(Jan-19-2022, 06:56 PM)deanhystad Wrote: Are you trying to use the new structural pattern matching introduced in Python 3.10?

Frankly i was reading on stackoverflow this https://stackoverflow.com/questions/6020...-in-python

After reading this i am not sure anymore it seems there is no switch case in Python.
According to this page https://data-flair.training/blogs/python-switch-case/ you can use dictionnary or with a function to replace the abscence of real method.

I dont want to enter in anything comlex, i am just stuying and trying experiences so i just thought there was an easy way to replace the if and elifs.
If it is to replace everything by a series of def, better use if and elif. As long as you dont have 30 choices.
Reply
#4
Having 30 if statements usually indicates you have a problem with your design. I've only been programming in Python for 2 years now, but I don't think I've ever needed more than 5, and I took that as an indication that my design should be improved.
Frankduc likes this post
Reply
#5
(Jan-19-2022, 07:00 PM)deanhystad Wrote: Are you trying to use the new structural pattern matching introduced in Python 3.10? As far as I know that is the only Python feature that uses "case" as a keyword. I have not installed 3.10 yet, but I believe the code would look like this:
while True:
    op = input(Select operation +, -, *, /: ")
    if op not in "+-*/":
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        match choice:
            case ['+']:
                print(num1, "+", num2, "=", num1 + num2)
            case ['-']:
                print(num1, "-", num2, "=", num1 - num2)
            case ['*']:
                print(num1, "*", num2, "=", num1 * num2)
            case ['/']:
                print(num1, "/", num2, "=", num1 / num2)
 
    if input("Let's do next calculation? (yes/no): ") == "no":
        break
I look forward to using this new feature. If I had to solve this problem without structured pattern matching I would probably fall back on using a dictionary.
operations = {
    "+": lambda a, b: print(f"{a} + {b} = {a+b}"),
    "-": lambda a, b: print(f"{a} - {b} = {a-b}"),
    "*": lambda a, b: print(f"{a} * {b} = {a*b}"),
    "/": lambda a, b: print(f"{a} / {b} = {a/b}"),
}

while True:
    op = input(f"Select operation {', '.join(operations.keys())}: ")
    if op not in operations:
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        operations[op](num1, num2)

    if input("Let's do next calculation? (yes/no): ") == "no":
        break

I had to tweak the code a little to get it to work.

while True:
    op = input("Select operation +, -, *, /: ")
    if op not in "+-*/":
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        match op:
            case '+':
                print(num1, "+", num2, "=", num1 + num2)
            case '-':
                print(num1, "-", num2, "=", num1 - num2)
            case '*':
                print(num1, "*", num2, "=", num1 * num2)
            case '/':
                print(num1, "/", num2, "=", num1 / num2)

    if input("Let's do next calculation? (yes/no): ") == "no":
        break
Output:
Select operation +, -, *, /: + Enter first number: 1 Enter second number: 1 1.0 + 1.0 = 2.0 Let's do next calculation? (yes/no): no
BashBedlam and Frankduc like this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
(Jan-19-2022, 07:50 PM)menator01 Wrote:
(Jan-19-2022, 07:00 PM)deanhystad Wrote: Are you trying to use the new structural pattern matching introduced in Python 3.10? As far as I know that is the only Python feature that uses "case" as a keyword. I have not installed 3.10 yet, but I believe the code would look like this:
while True:
    op = input(Select operation +, -, *, /: ")
    if op not in "+-*/":
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        match choice:
            case ['+']:
                print(num1, "+", num2, "=", num1 + num2)
            case ['-']:
                print(num1, "-", num2, "=", num1 - num2)
            case ['*']:
                print(num1, "*", num2, "=", num1 * num2)
            case ['/']:
                print(num1, "/", num2, "=", num1 / num2)
 
    if input("Let's do next calculation? (yes/no): ") == "no":
        break
I look forward to using this new feature. If I had to solve this problem without structured pattern matching I would probably fall back on using a dictionary.
operations = {
    "+": lambda a, b: print(f"{a} + {b} = {a+b}"),
    "-": lambda a, b: print(f"{a} - {b} = {a-b}"),
    "*": lambda a, b: print(f"{a} * {b} = {a*b}"),
    "/": lambda a, b: print(f"{a} / {b} = {a/b}"),
}

while True:
    op = input(f"Select operation {', '.join(operations.keys())}: ")
    if op not in operations:
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        operations[op](num1, num2)

    if input("Let's do next calculation? (yes/no): ") == "no":
        break

I had to tweak the code a little to get it to work.

while True:
    op = input("Select operation +, -, *, /: ")
    if op not in "+-*/":
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        match op:
            case '+':
                print(num1, "+", num2, "=", num1 + num2)
            case '-':
                print(num1, "-", num2, "=", num1 - num2)
            case '*':
                print(num1, "*", num2, "=", num1 * num2)
            case '/':
                print(num1, "/", num2, "=", num1 / num2)

    if input("Let's do next calculation? (yes/no): ") == "no":
        break
Output:
Select operation +, -, *, /: + Enter first number: 1 Enter second number: 1 1.0 + 1.0 = 2.0 Let's do next calculation? (yes/no): no

Seems to bump on match op:

Error:
match op: ^ SyntaxError: invalid syntax >
Still i do like the dictionnary option brought by deanhystad.
But this one if it works is closing from what i am use to in C#.

operations = {
    "+": lambda a, b: print(f"{a} + {b} = {a+b}"),
    "-": lambda a, b: print(f"{a} - {b} = {a-b}"),
    "*": lambda a, b: print(f"{a} * {b} = {a*b}"),
    "/": lambda a, b: print(f"{a} / {b} = {a/b}"),
}
 
while True:
    op = input(f"Select operation {', '.join(operations.keys())}: ")
    if op not in operations:
        print("Invalid Input")
    else:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
        operations[op](num1, num2)
 
    if input("Let's do next calculation? (yes/no): ") == "no":
        break
Great work from both of you for showing me the way in Python.
Reply
#7
Here one more as training,so it's a switch/case on steroids🧨
Python, match/case(structured pattern matching) is actually much more than a simple switch/case.

So a couple of thing can nest case together with | and case _: work as else:
I would say that code has a clean look,and quite readable even if not seen structured pattern matching before.
from operator import add, sub, mul, truediv

def calculate():
    us_in = input("Select operation +, -, *, /: ")
    n1 = int(input("Fist number: "))
    n2 = int(input("Second number: "))
    op = {
        "+": add(n1, n2),
        "-": sub(n1, n2),
        "*": mul(n1, n2),
        "/": truediv(n1, n2),
    }
    match us_in:
        case ("+"|"-"|"*"|"/") as calc:
            print(f'{n1} {us_in} {n2} = {op[calc]}\n')

def menu():
    while True:
        print("(1) Calculate two numbers")
        print("(Q) Quit")
        choice = input("Enter your choice: ").lower()
        match choice:
            case '1':
                calculate()
            case 'q':
                return
            case _:
                print(f"Not a correct choice <{choice}>,try again\n")

if __name__ == "__main__":
    menu()

Test that his work.
Output:
(1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: / Fist number: 9 Second number: 4 9 / 4 = 2.25 (1) Calculate two numbers (Q) Quit Enter your choice: car Not a correct choice <car>,try again (1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: * Fist number: 99 Second number: 5 99 * 5 = 495 (1) Calculate two numbers (Q) Quit Enter your choice: Q
Reply
#8
(Jan-20-2022, 06:28 AM)snippsat Wrote: Here one more as training,so it's a switch/case on steroids🧨
Python, match/case(structured pattern matching) is actually much more than a simple switch/case.

So a couple of thing can nest case together with | and case _: work as else:
I would say that code has a clean look,and quite readable even if not seen structured pattern matching before.
from operator import add, sub, mul, truediv

def calculate():
    us_in = input("Select operation +, -, *, /: ")
    n1 = int(input("Fist number: "))
    n2 = int(input("Second number: "))
    op = {
        "+": add(n1, n2),
        "-": sub(n1, n2),
        "*": mul(n1, n2),
        "/": truediv(n1, n2),
    }
    match us_in:
        case ("+"|"-"|"*"|"/") as calc:
            print(f'{n1} {us_in} {n2} = {op[calc]}\n')

def menu():
    while True:
        print("(1) Calculate two numbers")
        print("(Q) Quit")
        choice = input("Enter your choice: ").lower()
        match choice:
            case '1':
                calculate()
            case 'q':
                return
            case _:
                print(f"Not a correct choice <{choice}>,try again\n")

if __name__ == "__main__":
    menu()

Test that his work.
Output:
(1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: / Fist number: 9 Second number: 4 9 / 4 = 2.25 (1) Calculate two numbers (Q) Quit Enter your choice: car Not a correct choice <car>,try again (1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: * Fist number: 99 Second number: 5 99 * 5 = 495 (1) Calculate two numbers (Q) Quit Enter your choice: Q


I cant make it work, :

Error:
File "<string>", line 15 match us_in: ^ SyntaxError: invalid syntax >
Cant say what is wrong still trying to understand how it works. Wink
Reply
#9
(Jan-20-2022, 01:22 PM)Frankduc Wrote: ant say what is wrong still trying to understand how it works. Wink
This only work in Python 3.10 as structured pattern matching was new there,error message indicate that you run version less than this.
To recreate your error message.
Output:
# Running Python 3.10 G:\div_code\match_stuff λ py -3.10 match2.py (1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: - Fist number: 100 Second number: 50 100 - 50 = 50 (1) Calculate two numbers (Q) Quit Enter your choice: q # Now try in Python 3.9 G:\div_code\match_stuff λ py -3.9 match2.py File "G:\div_code\match_stuff\match2.py", line 13 match us_in: ^ SyntaxError: invalid syntax
Frankduc likes this post
Reply
#10
(Jan-20-2022, 01:32 PM)snippsat Wrote:
(Jan-20-2022, 01:22 PM)Frankduc Wrote: ant say what is wrong still trying to understand how it works. Wink
This only work in Python 3.10 as structured pattern matching was new there,error message indicate that you run version less than this.
To recreate your error message.
Output:
# Running Python 3.10 G:\div_code\match_stuff λ py -3.10 match2.py (1) Calculate two numbers (Q) Quit Enter your choice: 1 Select operation +, -, *, /: - Fist number: 100 Second number: 50 100 - 50 = 50 (1) Calculate two numbers (Q) Quit Enter your choice: q # Now try in Python 3.9 G:\div_code\match_stuff λ py -3.9 match2.py File "G:\div_code\match_stuff\match2.py", line 13 match us_in: ^ SyntaxError: invalid syntax

I am using online compilers, that explain. I am waiting to see what compiling program the school will suggest . I dont want to be force to reinstall some other compiler if i pick the wrong one. Windows already messy enough.
Thanks anyway ill keep the code and retry it in february.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  switch case not working Username0089098 1 672 Apr-09-2023, 05:49 AM
Last Post: buran
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 918 Feb-15-2023, 05:34 PM
Last Post: zsousa
  What colon (:) in Python mean in this case? Yapwc 4 2,051 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Merging two Data Frame on a special case piku9290dgp 0 1,069 Mar-02-2022, 10:43 AM
Last Post: piku9290dgp
  best way to use switch case? korenron 8 2,926 Aug-18-2021, 03:16 PM
Last Post: naughtyCat
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,639 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,834 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  Case sensitive checks kam_uk 2 1,968 Nov-30-2020, 01:25 AM
Last Post: bowlofred
  case transparent names in configpaser Skaperen 4 2,543 Oct-02-2020, 01:16 AM
Last Post: Skaperen
  How to break a loop in this case? Blainexi 10 7,155 Sep-24-2020, 04:06 PM
Last Post: Blainexi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020