Jan-19-2022, 08:09 PM
(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": 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
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": breakGreat work from both of you for showing me the way in Python.