Nerd Paradise

Don't worry, I'm not selling anything. Just giving a shoutout to one of my open-source side projects:

I created a programming language for beginners and am looking for people to test it out. If you have a spare moment (particularly if you haven't programmed before) and you're interested in making 2D games, please check it out.

Home > Programming > Switch Statements and Ternary Expressions in Python

Switch Statements and Ternary Expressions in Python

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]

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:
    case 1:
    case 2:
    /* 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

Another surprising gap in Python's feature list is ternary expressions. These can be spoofed by a similar means as switch statements.

Python treats True as a 1 and False as a 0, right? If you need an in-line conditional statement, create a tuple of size 2 follwed by the boolean conditional statement in brackets. Put the result for false in position 0 and the result for true in position 1.

print 'There ' + ('are cans','is a can')[tunacount == 1] + ' of tuna in my sock drawer'

You are visitor #002809
Get notified about new posts by following the newfangled twitter account.
Best viewed with
© 1999 Nerd Paradise