What's the purpose of the "and-or" trick?
i.e.
>>> a = ""
>>> b = "second"
>>> 1 and a or b
'second'
What's the purpose of the "and-or" trick?
i.e.
>>> a = ""
>>> b = "second"
>>> 1 and a or b
'second'
It was just a way to mimic the conditional operator (aka. "ternary" operator) found in the C family of languages. In the past, there was no direct equivalent expression. The following expressions are somewhat equivalent:
# in python
a and b or c
// in C
a ? b : c
Don't use it though. Due to the semantics of Python, if b
was falsy, the expression will evaluate to c
.
They have since provided a proper syntax for this construct as of Python 2.5 (PEP 308).
b if a else c