I just ran across this neat technique while reading wxPython in Action- A common operation is to output a string based on some expression being True or False. Being an assembly programmer at heart I usully code it as something like this:
if borked:In 'C' you can do this:
print "Its Borked"
else:
print "Its not Borked Yet"
borked ? "Its Borked" : "Its not Borked Yet"An alternative way in Python is to do it like this:
borked and "Its Borked" or "Its not Borked Yet"The expression is evaluated from left to right and it returns the result of the and if both are true, or the result of the or if the and fails. In Python instead of returning True for 'borked and "Its Borked" it returns the 2nd object, a string in this case, which is exactly what you want if borked is true. When it is false it goes on to the or expression and returns "Its not Borked Yet"
No comments:
Post a Comment