Jan-19-2022, 07:50 PM
(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
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags