More fun with Python (the ternary operator)
Tim Swast on , UpdatedThe ternary operator isn't necessary (Python didn't have one for years), but it can make code clearer when put to good use. The ternary operator consists of three parts: a condition, an expression to evaluate if the condition is true, and another expression to evaluate if the condition is false.
C and its relatives have a ternary operator that looks like the following:
(condition) ? (evaluate when true) : (evaluate when false);
Python users could use a normal if statement for this. But some programmers, who desired all the logic appear in single statement, resorted to cryptic uses of the 'and' and 'or' operators.
(evaluate_this_first) and (return_this_if_the_left_was_true)
(return_if_it_evaluates_as_true) or (return_if_left_evaluated_as_false)
PEP 308 adds a true ternary operator to Python:
(evaluate when true) if (condition) else (evaluate when false)
In my opinion, the Python ternary operator avoids some of the problems with C-style ternary operators. Since the Python code reads more like an English sentence, it's easier to remember which statement is evaluated when the condition is true and which is evaluated when the condition is false.