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?
#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


Messages In This Thread
How to use switch/case in python? - by newbieguy - Nov-07-2019, 06:35 PM
RE: How to use switch/case in python? - by ndc85430 - Nov-08-2019, 06:36 AM
RE: How to use switch/case in python? - by buran - Nov-08-2019, 09:15 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  switch case not working Username0089098 1 715 Apr-09-2023, 05:49 AM
Last Post: buran
  What colon (:) in Python mean in this case? Yapwc 4 2,220 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Switch case or match case? Frankduc 9 4,635 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  best way to use switch case? korenron 8 3,070 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,698 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,908 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  "Switch-to-spreadsheet" entry. Feasible in Python? whatspython 2 2,042 Sep-30-2020, 01:12 PM
Last Post: buran
  How do I do this? Switch Case? mstichler 4 2,611 Jun-05-2020, 10:27 AM
Last Post: snippsat
  How to switch table area coordinates in Python Camelot and Tabula-Py john5 0 4,307 May-08-2019, 04:31 PM
Last Post: john5
  switch limitations MuntyScruntfundle 3 2,417 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