64

How can I do something like var foo = (test) ? "True" : "False"; in Python (specifically 2.7)?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
cynicaljoy
  • 2,047
  • 1
  • 18
  • 25

2 Answers2

94

PEP 308 adds a ternary operator:

foo = "True" if test else "False"

It's been implemented since Python 2.5

Brian McKenna
  • 45,528
  • 6
  • 61
  • 60
-1

This one looks a bit more like original ternary:

foo=a and b or c
Frost.baka
  • 7,851
  • 2
  • 22
  • 18
  • `f = a or b or c` works the same as in javascript (it returns the first truthy value). – Hakim Dec 31 '13 at 18:40
  • 6
    -1 Beware, there is a case where this does not work: if the condition `a` is True and `b` is any false value, such as False, 0, None, [], {} and so on, then the result is `c`, which is wrong (it should be `b`). For example, (True and [] or [1,2,3]) is equal to [1,2,3], while ([] if True else [1, 2, 3]) is equal to [], as it should be. I recommend sticking to the official ternary operator. – MiniQuark Mar 03 '17 at 15:03