Jan-20-2022, 06:28 AM
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
I would say that code has a clean look,and quite readable even if not seen structured pattern matching before.
Test that his work.
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