Switch Statements in Python

{<1>}Python

Anyone familiar with Java, C, C++, or another similar language would easily recognize this code:


switch (n) {
  case 0:
    puts("You typed zero.");
    break;
  case 9:
    puts("You typed nine.");
    break;
  default:
    puts("You didn’t type Zero or Nine.");
    break;
}

This is a simple switch statement, generally used when IF-THEN-ELSE blocks would be overly complex or unwieldy. Python, however, doesn’t have switch { case } syntax, so we have to be a little clever. The most obvious way to duplicate the above code would be:


if n == 0:
    print "You typed zero."
elif n == 5:
    print "You typed five."
elif n == 9:
    print "You typed nine."
else:
    print "You didn't type zero or nine."

That’ll work, but its a little wasteful when it comes to line count or more complex cases. We can simplify this quite a bit by making use of Python dictionaries:


cases = {0 : "You typed zero.",
         5 : "You typed five.",
         9 : "You typed nine."}
if n in cases.keys():
    print cases[n]
else:
    print "You didn't type zero or nine."

In that example, every possible case is placed as a dictionary key and the string to be printed is the value. In this example we only save 1 line of code, but we also cut the execution time drastically. On my machine (Core i7 920), example-1 takes 4.999ms to execute. Example-2, on the other hand takes only 1.999ms; this means its a speedup of roughly 250%. An extra 3ms may not be much, but in complex cases, limited hardware environments, or extremely time sensitive application it does.

Finally, we have one more example. What if you want to call functions instead of print strings? Thats easily done with almost the same code:


cases = {0 : Object.function_1,
         5 : Object.function_2,
         9 : Object.function_3}
if n in cases.keys():
    cases[n]()
else:
    Object.default()

In this example, each function call (minus the calling parenthesis) is placed as the value of its respective key. Since we don’t include the parenthesis, the function isn’t called yet. Then, on line 5, we select the appropriate function and call it.