Login | Register
Nerd ParadiseArtisanal tutorials since 1999

Switch Statements

elif's got you down? It's ok, I feel your pain. Python has extremely flexible syntax and has lots of weird quirks and constructs that let you do powerful things in a short amount of code. But in all it's grandeur, there are no switch statements! How frustrating.

So as a public service, I will teach you how to simulate the efficiency of a switch statement in Python.

switcharoo = [action0, action1, action2, action3, action4, ...]
command = switcharoo[some number]
command()

Basically, what you can do is construct a list of function pointers. Then you treat the selecting of an index number as your switch. This code in a C-style language would look like this...

switch (x) {
    case 0:
        action0();
    case 1:
        action1();
    case 2:
        action2();
    /* and so on... */
}

Of course, you could use lambda's instead of function pointers if you're all hard core like that. Just be careful not to put coded expressions in your list, or else they'll evaluate before the switch occurs which could be bad in certain cases.

You could also use a dictionary construct and apply the same concept with strings!

Ternary Expressions in Python

If you're used to the C style condition ? expr1 : expr2 syntax, then this may feel a bit backwards. Place the true expression first, followed by the if keyword, followed by the condition, followed by else followed by the false condition. It's often best to wrap all that in parentheses to make the grouping unambiguous:
print("I have " + str(total) + " can" + ("" if total == 1 else "s") + " of tuna.")

Hey, there, Python folks. Hope you enjoyed the post. I just wanted to give a quick shout-out for a weekly Python code golf that I recently started up over on StringLabs.io. If you like Python puzzles please come check it out!