Python Forum
How to use switch/case in python? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to use switch/case in python? (/thread-22313.html)



How to use switch/case in python? - newbieguy - Nov-07-2019

Hi everyone! If you can see, I am totally newbie in python.
I want to create easy calculator used with switch/case statement.
My idea is:
def add(a,b):
    return a+b
def substract(a,b):
    return a-b
def divide(a,b):
    return a/b
def multiplication(a,b):
    return a*b
def increase(a, b):
    return a ** b
print ("Enter first number!")
a = float(input("First number = "))
b = float(input("Second Number = "))
print ("You entered:",a," and ",b)
print("::Menu::")
print("1 - Add")
print("2 - Substract")
print("3 - Multiply")
print("4 - Divide")
print("5 - Increase")
print("6 - Exit")
choice = str(input("What you want do to:?\n")),

def multiple_choice(choice,a,b):
    wybor= {
        '1': add(a,b),
        '2': substract(a,b),
        '3': multiplication(a,b),
        '4': divide(a,b),
        '5':increase(a, b),
        '6':sys.exit
  }.get(choice,a,b)
Could anyone help me to initiate properly multiple_choice? Thanks for help!


RE: How to use switch/case in python? - kozaizsvemira - Nov-07-2019

I am not master at python, but following code works:

def add(a,b):
    return a+b
def substract(a,b):
    return a-b
def divide(a,b):
    return a/b
def multiplication(a,b):
    return a*b
def increase(a, b):
    return a ** b
 
def multiple_choice():
    print ("Enter first number!")
    a = float(input("First number = "))
    b = float(input("Second Number = "))
    print ("You entered:",a," and ",b)
    print("::Menu::")
    print("1 - Add")
    print("2 - Substract")
    print("3 - Multiply")
    print("4 - Divide")
    print("5 - Increase")
    print("6 - Exit")
    choice = str(input("What you want do to:?\n"))

    if choice == '1':
        print('Your solution is:', add(a, b))
    elif choice == '2':
        print('Your solution is:', substract(a, b))
    else:
        print('Please input 1 to 6')

multiple_choice()
If you want result without decimals instead of float use int. Just add elif choice == 3...etc.


RE: How to use switch/case in python? - newbieguy - Nov-07-2019

I agree,your code works,but you used if statement, I like'd to learn how to use switch/case statement
For example ( I took it from: www.pydanny.com/why-doesnt-python-have-switch-case.html)
def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
    return switcher.get(argument, "nothing")



RE: How to use switch/case in python? - ichabod801 - Nov-07-2019

There is no switch/case statement in Python. Use if/elif instead or a data structure. You did use a data structure, but I would do it this way:

operators = {'1': add, '2': subtract, '3': divide, '4': multiply, '5': increase}
...
if choice in operators:
    print(operators[choice](a, b))



RE: How to use switch/case in python? - newbieguy - Nov-07-2019

Quote:There is no switch/case statement in Python. Use if/elif instead or a data structure. You did use a data structure, but I would do it this way:
Yea I know it,I wanted to know way that is being similar like switch/case,because this is very useful option.


RE: How to use switch/case in python? - kozaizsvemira - Nov-07-2019

(Nov-07-2019, 07:06 PM)newbieguy Wrote:
Quote:There is no switch/case statement in Python. Use if/elif instead or a data structure. You did use a data structure, but I would do it this way:
Yea I know it,I wanted to know way that is being similar like switch/case,because this is very useful option.

I've never worked with switches never thought about it, but found a solution

a = int(input('First num:'))
b = int(input('Second num:'))

def add():
    return a + b

def subtract():
    return a - b
 
# Your Input
choice = input('Choose:')
 
choices = {
    '1': add(), 
    '2': subtract()
    }
 
result = choices.get(choice, 'default')
 
print(result)



RE: How to use switch/case in python? - newbieguy - Nov-07-2019

I appreciate that you found a solution and shared with it ! Thank you bro,this theme is solved.


RE: How to use switch/case in python? - ndc85430 - Nov-08-2019

(Nov-07-2019, 07:06 PM)newbieguy Wrote:
Quote:There is no switch/case statement in Python. Use if/elif instead or a data structure. You did use a data structure, but I would do it this way:
Yea I know it,I wanted to know way that is being similar like switch/case,because this is very useful option.

Do you understand that the values in the dictionary are functions? It turns out to be very useful to be able to store and pass around functions like you can with other values (ints, strings, etc.). For this specific example, one needn't write their own implementations of these functions if they don't want to - take a look at the operator module.


RE: How to use switch/case in python? - buran - Nov-08-2019

(Nov-08-2019, 06:36 AM)ndc85430 Wrote: Do you understand that the values in the dictionary are functions?
actually in the current implementation they call/execute all functions in the dict at the time when it is defined i.e. at the moment it's a dict of calculated results using global variables, not functions. And that is bad

Also functions should take operands as arguments (like in OP original code), not use global variables.
def add (a, b):
    return a + b

def substract(a, b):
    return a - b

math_functions = {'1':add, '2':substract}

user_func = input('What math operation (1 for add, 2 for substract): ')
num1 = int(input('Enter first integer number: '))
num2 = int(input('Enter second integer number: '))
print(math_functions[user_func](num1, num2))
Output:
What math operation (1 for add, 2 for substract): 1 Enter first integer number: 10 Enter second integer number: 3 13
the code is bare-bone, i.e. no checks for invalid input, etc. Also as ndc85430 wrote - one can use operator module from standard library

Also check our tutorial: https://python-forum.io/Thread-if-structure-converted-to-dictionary
it's a perfect fit for your case


RE: How to use switch/case in python? - newbieguy - Nov-08-2019

Final code:
def add(a, b) :
    return a + b
def substract(a, b) :
    return a - b
def divide(a, b) :
    return a / b
def multiplication(a, b) :
    return a * b
def increase(a, b) :
    return a ** b


math_functions = {'1' : add, '2' : substract,'3':divide,'4':multiplication,'5':increase}
print ("Enter first number!")
a = float(input("First number = "))
b = float(input("Second Number = "))
print("You entered:", a, " and ", b)
print("::Menu::")
print("1 - Add")
print("2 - Substract")
print("3 - Divide")
print("4 - Multipy")
print("5 - Increase")
print("6 - Exit")
user_func = input('What math operation?:')
if user_func =='6':
    exit()
    
print("Your Solution is: ",math_functions[user_func](a, b))
Thanks for your help.