6 ms·
That is pythons 'ternary operator', you can nest it: x = 11 if False else ( 12 if False else 13) print x => 13 Python's philosophy in general is to try
by mahyarm 12y ago
That is pythons 'ternary operator', you can nest it:
x = 11 if False else ( 12 if False else 13)
print x
=> 13
Python's philosophy in general is to try to avoid magic symbols such as && or || and just use 'and' and 'or'
- keypusher 12y agoYou can actually just use the 'or' to shortcut this whole thing, because or returns the first true value. x = False or (True or False)
- philsnow 12y agoOr you can write it all out on multiple lines if cond1: if cond2: x = 12 else: x = 11 else: x = 13 That way you can debug it more easily (because you can trace execution rather than printing out the values that cond1 and cond2 depend on and figuring out in your head which way the ternary will go). This also removes ambiguity in the case where you might want to assign to x some falsey thing like None or [] or zero: >>> y = None >>> x = False or ( y or False ) >>> x False The above code depends on the value of y for control flow. Clearer is to use syntax for control flow and not abuse falsey-ness or truthiness. >>> print [bool(f) for f in [None, 0, 0.0, [], ()]] [False, False, False, False, False] If you really do want to test the falsey behavior, IMHO it's much, much clearer to branch on bool(the_maybe_falsey_thing) rather than just the_maybe_falsey_thing.
- hueving 12y ago>If you really do want to test the falsey behavior, IMHO it's much, much clearer to branch on bool(the_maybe_falsey_thing) rather than just the_maybe_falsey_thing. Maybe if you never program in python. Otherwise it makes absolutely no sense to do so because its obvious that every value is evaluated for its boolean value.
- dreamweapon 12y agoRight. But at no point was I saying that Python ought to have a ternary op, or that it doesn't have an analogous construct.