Python If Else Assignment Management

6. Ternary Operators¶

Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. They became a part of Python in version 2.4

Here is a blueprint and an example of using these conditional expressions.

Blueprint:

Example:

It allows to quickly test a condition instead of a multiline if statement. Often times it can be immensely helpful and can make your code compact but still maintainable.

Another more obscure and not widely used example involves tuples. Here is some sample code:

Blueprint:

Example:

This works simply because True == 1 and False == 0, and so can be done with lists in addition to tuples.

The above example is not widely used and is generally disliked by Pythonistas for not being Pythonic. It is also easy to confuse where to put the true value and where to put the false value in the tuple.

Another reason to avoid using a tupled ternery is that it results in both elements of the tuple being evaluated, whereas the if-else ternary operator does not.

Example:

This happens because with the tupled ternary technique, the tuple is first built, then an index is found. For the if-else ternary operator, it follows the normal if-else logic tree. Thus, if one case could raise an exception based on the condition, or if either case is a computation-heavy method, using tuples is best avoided.

condition_is_trueifconditionelsecondition_is_false
is_fat=Truestate="fat"ifis_fatelse"not fat"
(if_test_is_false,if_test_is_true)[test]
fat=Truefitness=("skinny","fat")[fat]print("Ali is ",fitness)# Output: Ali is fat
condition=Trueprint(2ifconditionelse1/0)#Output is 2print((1/0,2)[condition])#ZeroDivisionError is raised

I wouldn’t say CoffeeScript is screwed – it’s just the consequence of allowing the if-the-else construct as an expression. Scala also allows this as does Ruby (although Ruby also has the test ? true_v : false_v expression – but then Ruby also evaluates everything as true except and – including 0, 0.0 and empty collections – you want uniformity?).

Given the lack of new semantics, it is obvious to a newbie programmer what is going on, although it does allow the possibility of nightmarish nested if-then-(if-then-else)-else-(if-then-else) tangles. I have had in the past a programmer come to me and say “I haven’t a clue what is meant by this!!” when confronted with the C style ternary op – but that was before widespread availability of the Internet. And certain managers I have know went apoplectic at the use of the C ternary op to the point of banning it in coding standards completely – but generally because it could be abused the same way as if-then-else as an expression.

I guess BDFL did not want to introduce new terms into the language syntax – and were already there, while at the same time avoiding the pitfalls of . Also you would have to be crazy to abuse the syntax, which although awkward, kind of suppresses the following abuses even in the most operator-obsessive programmer.

####
from itertools import combinations_with_replacement as cwr
def foo(a, b, c):
return (1 if b else 2) if a else (3 if c else 4) # ugh

for t in cwr((False, True), 3):
print “foo{} :-> {}”.format(t, foo(*t))
####

It works! But it does introduce a certain amount of self policing. But you would see it a lot more if BDFL had allowed:

#### won’t work
def foo(a, b, c):
return a? (b? 1: 2) : (c? 3: 4) # I knew quite a few people who liked to do this
####

or even

#### won’t work either
def foo(a, b, c):
return if a: (if b: 1 else: 2) else: (if c: 3 else: 4) # probably wrecks the parser!!!
####

And that’s what he was on about with a language that insisted on indentation in the first place I imagine.

0 Replies to “Python If Else Assignment Management”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *