Python Forum
How to use switch/case in python?
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!
Reply
#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.
Reply
#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: 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")
Reply
#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))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#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.
Reply
#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)
Reply
#7
I appreciate that you found a solution and shared with it ! Thank you bro,this theme is solved.
Reply
#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.
Reply
#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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  switch case not working Username0089098 1 672 Apr-09-2023, 05:49 AM
Last Post: buran
  What colon (:) in Python mean in this case? Yapwc 4 2,051 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Switch case or match case? Frankduc 9 4,385 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  best way to use switch case? korenron 8 2,926 Aug-18-2021, 03:16 PM
Last Post: naughtyCat
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,639 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,834 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  "Switch-to-spreadsheet" entry. Feasible in Python? whatspython 2 1,976 Sep-30-2020, 01:12 PM
Last Post: buran
  How do I do this? Switch Case? mstichler 4 2,499 Jun-05-2020, 10:27 AM
Last Post: snippsat
  How to switch table area coordinates in Python Camelot and Tabula-Py john5 0 4,213 May-08-2019, 04:31 PM
Last Post: john5
  switch limitations MuntyScruntfundle 3 2,336 Jan-27-2019, 06:11 PM
Last Post: aakashjha001

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020