Jan-19-2022, 07:00 PM
(This post was last modified: Jan-19-2022, 07:29 PM by deanhystad.)
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