Is there a way to write this C/C++ code in Python?
a = (b == true ? "123" : "456" )
Asked
Active
Viewed 1.6e+01k times
140

Karl Knechtel
- 62,466
- 11
- 102
- 153

huy
- 4,782
- 6
- 36
- 42
-
It's called a ternary-if, by the way. http://en.wikipedia.org/wiki/%3F:, http://en.wikipedia.org/wiki/Ternary_operation – GManNickG Nov 06 '09 at 09:16
-
... or "conditional expression" – Oren S Nov 06 '09 at 11:27
4 Answers
254
a = '123' if b else '456'

SilentGhost
- 307,395
- 66
- 306
- 293
-
10
-
2For future reference, here's the Python documentation for the conditional expression: http://docs.python.org/reference/expressions.html#boolean-operations – Greg Hewgill Nov 06 '09 at 09:25
-
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
-
1I 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
-
1That 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
-
5Whilst 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
-