Switch case or match case? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Switch case or match case? (/thread-36135.html) |
Switch case or match case? - Frankduc - Jan-19-2022 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 RE: Switch case or match case? - deanhystad - Jan-19-2022 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": breakI 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 RE: Switch case or match case? - Frankduc - Jan-19-2022 (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/60208/replacements-for-switch-statement-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. RE: Switch case or match case? - deanhystad - Jan-19-2022 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. RE: Switch case or match case? - menator01 - Jan-19-2022 (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: 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
RE: Switch case or match case? - Frankduc - Jan-19-2022 (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: Seems to bump on match op: 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": breakGreat work from both of you for showing me the way in Python. RE: Switch case or match case? - snippsat - Jan-20-2022 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.
RE: Switch case or match case? - Frankduc - Jan-20-2022 (Jan-20-2022, 06:28 AM)snippsat Wrote: Here one more as training,so it's a switch/case on steroids🧨 I cant make it work, : Cant say what is wrong still trying to understand how it works.
RE: Switch case or match case? - snippsat - Jan-20-2022 (Jan-20-2022, 01:22 PM)Frankduc Wrote: ant say what is wrong still trying to understand how it works.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.
RE: Switch case or match case? - Frankduc - Jan-20-2022 (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.This only work in Python 3.10 as structured pattern matching was new there,error message indicate that you run version less than this. 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. |