Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 How to use switch/case in python?
#1
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!
Quote
#2
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.
Gribouillis likes this post
Quote
#3
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: http://www.pydanny.com/why-doesnt-python...-case.html)
def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
    return switcher.get(argument, "nothing")
Quote
#4
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))
metulburr likes this post
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#5
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.
Quote
#6
(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)
baquerik likes this post
Quote
#7
I appreciate that you found a solution and shared with it ! Thank you bro,this theme is solved.
Quote
#8
(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.
Quote
#9
(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
Quote
#10
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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  How to switch table area coordinates in Python Camelot and Tabula-Py john5 0 718 May-08-2019, 04:31 PM
Last Post: john5
  How to write switch case statement in Python pyhelp 9 1,898 Nov-11-2018, 08:53 PM
Last Post: woooee
  Is there a something like "case" in Python 3.6? Raptor88 18 6,697 Feb-27-2017, 02:44 AM
Last Post: Raptor88

Forum Jump:


Users browsing this thread: 1 Guest(s)