Falling in Love with Python, Imitating the "Switch" Statement

I've been wanting to get my hands dirty with desktop software, so I've decided to play around with Python.

It's only been about two weeks, and I've already got the basic syntax down pat. Now I've been messing around with application/systems programming, and have been reading up on wxPython and PyGame. Talk about ease of use. Python is my new baby.

There is no equivalent to the "Switch" statement that you find in most C based languages, you have to use "if/elif/else" statements, which as you all know can cause a lot of typing. But you can use Dictionaries and their Key's to emulate a "Switch" statement.

Take a look at this "if/elif/else" statement:

my_choice = "print_help"
 
if my_choice == "print_hello":
    print "How's it going."
elif my_choice == "print_help":
    print "How can I help you?"
elif my_choice == "print_goodbye":
    print "See you later."
else:
    print 

Here's how you could use a Dictionary and it's Key's to emulate a "Switch" statement:

my_choice = "print_help"
 
print { "print_hello": "How's it going.",
    "print_help": "How can I help you?",
    "print_goodbye": "See you later." }[my_choice]

(Note how we select the Key using "[my_choice]" at the end of the dictionary definition)

Now that's a little less typing with the same results. Not bad.

You can also add an "else" clause using the Dictionary "has_key"
test or "get" method call. Here's an example using the Dictionary "get" method:

my_choice = "print_say_something"
 
choices = { "print_hello": "How's it going.",
    "print_help": "How can I help you?",
    "print_goodbye": "See you later." }
 
print choices.get(my_choice, "That was not an option")

To take it a bit further, we can build the dictionary dynamically, and return function names so we can keep the dictionary nice and clean. Check out this next example:

def func1():
    print "How's it going."
 
def func2():
    print "How can I help you?"
 
def func3():
    print "See you later."
 
func_choice = {"print_hello": func1,
    "print_help": func2,
    "print_goodbye": func3}
 
choose_function = "print_help"
 
func_choice[choose_function]()

Here is a way to run larger blocks of code that have been encapsulated in functions. This will keep your "Switch" dictionary nice and clean, while enabling you to execute larger blocks of code.