The Ternary Operator is really handy for refactoring a simple if else statement into one line of code. Unfortunately, Python doesn’t have the standard ? : operator built in. So, what should you do to refactor your code?

Update: I just found via this StackOverflow answer that Python versions 2.5 and higher have the following syntax for the Ternary operator:

As you can see, if the “and” statement is evaluated to True, then the last item of the and statement is returned (in this case a). Alternatively, if the “and” statement is evaluated to False, the last item of the or statement is returned (in this case b).

When The Trick Goes Horribly Wrong

However, there is a bit of loophole with this logic! If a is a falsy value, then the “and” statement is evaluated to False and b is returned instead of a, even if the first item is evaluated to True!