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.
Switch Statements and Ternary Expressions in Python
Switch Statementselif'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.
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...
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 PythonAnother 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.