Posts: 201
Threads: 37
Joined: Dec 2021
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
Posts: 6,794
Threads: 20
Joined: Feb 2020
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":
break I 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
menator01 and Frankduc like this post
Posts: 201
Threads: 37
Joined: Dec 2021
Jan-19-2022, 07:05 PM
(This post was last modified: Jan-19-2022, 07:05 PM by Frankduc.)
(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/6020...-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.
Posts: 6,794
Threads: 20
Joined: Feb 2020
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.
Posts: 1,145
Threads: 114
Joined: Sep 2019
(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":
break I 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
Frankduc and BashBedlam like this post
Posts: 201
Threads: 37
Joined: Dec 2021
(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":
break I 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":
break Great work from both of you for showing me the way in Python.
Posts: 7,319
Threads: 123
Joined: Sep 2016
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.
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
Posts: 201
Threads: 37
Joined: Dec 2021
(Jan-20-2022, 06:28 AM)snippsat Wrote: 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.
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
I cant make it work, :
Error: File "<string>", line 15
match us_in:
^
SyntaxError: invalid syntax
>
Cant say what is wrong still trying to understand how it works.
Posts: 7,319
Threads: 123
Joined: Sep 2016
Jan-20-2022, 01:32 PM
(This post was last modified: Jan-20-2022, 01:33 PM by snippsat.)
(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.
Output: # Running Python 3.10
G:\div_code\match_stuff
λ py -3.10 match2.py
(1) Calculate two numbers
(Q) Quit
Enter your choice: 1
Select operation +, -, *, /: -
Fist number: 100
Second number: 50
100 - 50 = 50
(1) Calculate two numbers
(Q) Quit
Enter your choice: q
# Now try in Python 3.9
G:\div_code\match_stuff
λ py -3.9 match2.py
File "G:\div_code\match_stuff\match2.py", line 13
match us_in:
^
SyntaxError: invalid syntax
Posts: 201
Threads: 37
Joined: Dec 2021
(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.
To recreate your error message.
Output: # Running Python 3.10
G:\div_code\match_stuff
λ py -3.10 match2.py
(1) Calculate two numbers
(Q) Quit
Enter your choice: 1
Select operation +, -, *, /: -
Fist number: 100
Second number: 50
100 - 50 = 50
(1) Calculate two numbers
(Q) Quit
Enter your choice: q
# Now try in Python 3.9
G:\div_code\match_stuff
λ py -3.9 match2.py
File "G:\div_code\match_stuff\match2.py", line 13
match us_in:
^
SyntaxError: invalid syntax
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.
|