140

Is there a way to write this C/C++ code in Python? a = (b == true ? "123" : "456" )

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
huy
  • 4,782
  • 6
  • 36
  • 42

4 Answers4

254
a = '123' if b else '456'
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
25

While a = 'foo' if True else 'bar' is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:

a = (b == True and "123" or "456" )

... which in python should be shortened to:

a = b is True and "123" or "456"

... or if you simply want to test the truthfulness of b's value in general...

a = b and "123" or "456"

? : can literally be swapped out for and or

jdi
  • 90,542
  • 19
  • 167
  • 203
  • 1
    I should note that the and..or approach here can backfire on you if the "123" value were actually an empty string or evaluates to a false value. The if..else is a bit safer. – jdi Apr 29 '14 at 19:56
21

My cryptic version...

a = ['123', '456'][b == True]
Socram
  • 219
  • 2
  • 2
  • 1
    That was one of the old approaches before the single-line if statement was possible, right? Kind of like how you can do it with logical: `True and "foo" or "bar" ` – jdi May 02 '12 at 22:49
-1

See PEP 308 for more info.

Jason Sundram
  • 12,225
  • 19
  • 71
  • 86
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 5
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – clickbait Aug 04 '18 at 03:44
  • This is not an elaborative answer, I dont see it helpful – JeanCarlos Chavarria Jul 30 '19 at 22:34