2

What's the purpose of the "and-or" trick?

i.e.

>>> a = ""

>>> b = "second"

>>> 1 and a or b

'second'
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
ThePhantom05
  • 139
  • 1
  • 1
  • 11
  • It’s like an inline `if` that works less reliably. – Ry- Oct 25 '13 at 15:19
  • 2
    To be specific, you’re seeing it work less reliably here, because `a` is falsy. With anything truthy, it would work like `a if 1 else b`. – Ry- Oct 25 '13 at 15:27
  • Yea, I should check to see if a is never false. I'm more asking why I would use the "and-or" trick instead of an if-statement? – ThePhantom05 Oct 25 '13 at 15:31
  • Also read: http://stackoverflow.com/questions/3826473/boolean-operations-in-python-ie-the-and-or-operators – NullUserException Oct 25 '13 at 15:37

1 Answers1

8

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
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272