(Feb-25-2017, 11:22 AM)ichabod801 Wrote:(Feb-25-2017, 10:33 AM)Raptor88 Wrote: Reply to zivoni: 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.
Oh, I thought zivoni's comment about the "dictionary mapping" approach was an alternative to what Mekire had posted.
Newbie error on my part.
(Feb-25-2017, 11:33 AM)snippsat Wrote:(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 andget()
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)
snippsat,
Thank you for taking the time to key in the comparison code. Very helpful for a newbie to try to understand what's happening. Studying every line now.
Thanks.
(Feb-25-2017, 12:18 PM)wavic Wrote: 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]()
Studying your example. What's the reason for all of the leading "...:" dots and colon? Have not seen that in any Python tutorial.
Thanks.