Python Forum

Full Version: How to use switch/case in python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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.
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")
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))
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.
(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)
I appreciate that you found a solution and shared with it ! Thank you bro,this theme is solved.
(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.
(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-struct...dictionary
it's a perfect fit for your case
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.