Python Forum
Is there a something like "case" in Python 3.6?
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a something like "case" in Python 3.6?
#1
It's been too many years since I programed in C but I remember the "switch" method of comparing and doing things.  Something like this:

# This is a "C" example, not Python:

switch (user-input)     #user-input will be .3 or .4 or .5 .... to .9
{
    case .3:
        // code to be executed if user-input is equal to .3;
        break;

    case .4:
        // code to be executed if user-input is equal to .4;
        break;
        .
        .
    default:
        // code to be executed if user-input doesn't match any constant
}
Does Python 3.6 have a similar way of testing for equality against a list of constant values, that is clean and easy to understand?  Other than doing nested "if ... elif" statements.
Reply
#2
The "if...elif...else" statement https://docs.python.org/3/tutorial/controlflow.html
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
In python we switch on dictionaries.

A brief (and silly) example:
def func_one():
    print("Hey from func one.")

def func_two():
    print("Hey from func two.")

def default():
    print("I'm some default func.")


SWITCH_DICT = {".3" : func_one, ".4" : func_two}


user_input = input("Enter .3 or .4: ")
SWITCH_DICT.get(user_input, default)()
Output:
Enter .3 or .4: .3 Hey from func one.
Output:
Enter .3 or .4: .4 Hey from func two.
Output:
Enter .3 or .4: spam I'm some default func.
This technique is extremely common and useful in a wide variety of situations.
Reply
#4
(Feb-24-2017, 08:38 PM)Mekire Wrote: In python we switch on dictionaries.
A brief (and silly) example:

.... snip to save bandwidth ....

This technique is extremely common and useful in a wide variety of situations.

Hey Mekire,

Looks good.  I'll try some code later after completing my "Honey dos" Wink

BTW, could you explain how one "likes" a post?  Probably obvious and I see people doing that, but I can't see the forest for the trees.

Thanks.
Reply
#5
Sometimes switch could be replaced with a lighter "dictionary mapping" approach when you either find values directly in a dictionary (it could be better to "prepopulate" dictionary with numbers 1-1000 instead of doing switch if x < 30 -> x*3, if x < 100 -> x*2, if ... repeatedly), or you lookup a  bunch of parameters and feed it to some "universal" function.

But if you are trying to replace some "evil" sort of switch with lots of falling through / conditional breaks, then it could be problematic.

There is "like" button on right side at the bottom of post, next to quote buttons.
Reply
#6
(Feb-24-2017, 10:11 PM)zivoni Wrote: Sometimes switch could be replaced with a lighter "dictionary mapping" approach when you either find values directly in a dictionary (it could be better to "prepopulate" dictionary with numbers 1-1000 instead of doing switch if x < 30 -> x*3, if x < 100 -> x*2, if ... repeatedly), or you lookup a  bunch of parameters and feed it to some "universal" function.

But if you are trying to replace some "evil" sort of switch with lots of falling through / conditional breaks, then it could be problematic.

There is "like" button on right side at the bottom of post, next to quote buttons.

If there is some short code for the "dictionary mapping" approach that you can post, or a link to a simple explanation, would appreciate that.

Regarding the "like" button, I didn't see it since the sample post that I happened to use was my own post.  Not that I wanted to like my own post but that just happened to be in view when I examined all of the buttons.  Looking at posts by others, I now see the "like" button.  Thanks!
Reply
#7
(Feb-25-2017, 10:33 AM)Raptor88 Wrote: If there is some short code for the "dictionary mapping" approach that you can post, or a link to a simple explanation, would appreciate that.

Mekire posted some code (four posts up). Basically, the keys of the dictionary are the values you would switch on. The values of the dictionary are the results of the switch. Since Python functions are first class objects, and can be values in dictionaries, you can get rather complicated behavior using a dictionary this way.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
(Feb-25-2017, 10:33 AM)Raptor88 Wrote: If there is some short code for the "dictionary mapping" approach that you can post, or a link to a simple explanation, would appreciate that.
Can make one more:
color = 'red' # From eg user input
if color == 'red':
   set_color = 'rgb(255,0,0)'
elif color == 'blue':
   set_color = 'rgb(0,0,255)'
elif color == 'green':
   set_color = 'rgb(0,128,0)'
else:
   print('No rgb for that color')

print(set_color) #--> rgb(255,0,0)
With dictionary and get() method.
color = 'red' # From eg user input
choices = {'red': 'rgb(255,0,0)', 'blue': 'rgb(0,0,255)', 'green': 'rgb(0,128,0)'}
set_color = choices.get(color, 'No rgb for that color')
print(set_color) #--> rgb(255,0,0)
Reply
#9
That is ingenious. I would have thought an eval() statement would have been required to make that work. The more I deal with Python the more I like it.
Reply
#10
As @ichabod801 said the Python functions are first-class objects. I don't know what first-class means but I know that I can make a reference to a function. For example print():

In [1]: say = print

In [2]: def yes_ans():
   ...:     say("OK, wiping C: drive in progress. It will take some time.")
   ...:     

In [3]: def no_ans():
   ...:     say("OK, C: drive zero fill is starting now. Be patient!")
   ...:     

In [4]: action = {'yes': yes_ans, 'no': no_ans}

In [5]: while True:
   ...:     answer = input("Would you like to free some space on C:?[yes/no]: ")
   ...: 
   ...:     if answer.lower() in action:
   ...:         action[answer.lower()]()
   ...:         break
   ...:     
Would you like to free some space on C:?[yes/no]: no
OK, C: drive zero fill is starting now. Be patient!
Here the references to yes_ans and no_ans are stored in a dictionary and you check for the key then get the value of the key which is the function name. To call the function you have to put brackets after the dict[function]: dict[function]()
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What colon (:) in Python mean in this case? Yapwc 4 2,161 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Switch case or match case? Frankduc 9 4,515 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,674 Jul-27-2021, 02:02 PM
Last Post: Suriya
  Help: write 'case' with Python ICanIBB 2 1,872 Jan-27-2021, 09:39 PM
Last Post: Larz60+
  How to use switch/case in python? newbieguy 9 4,059 Nov-08-2019, 11:35 AM
Last Post: newbieguy
  How to write switch case statement in Python pyhelp 9 9,213 Nov-11-2018, 08:53 PM
Last Post: woooee

Forum Jump:

User Panel Messages

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