Is there a way to write this C/C++ code in Python?
a = (b == true ? "123" : "456" )
-
It's called a ternary-if, by the way. en.wikipedia.org/wiki/%3F:, en.wikipedia.org/wiki/Ternary_operationGManNickG– GManNickG2009-11-06 09:16:04 +00:00Commented Nov 6, 2009 at 9:16
-
... or "conditional expression"Oren S– Oren S2009-11-06 11:27:01 +00:00Commented Nov 6, 2009 at 11:27
Add a comment
|
4 Answers
a = '123' if b else '456'
3 Comments
David Webb
This ternary operator was introduced in Python 2.5.
Greg Hewgill
For future reference, here's the Python documentation for the conditional expression: docs.python.org/reference/expressions.html#boolean-operations
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
1 Comment
jdi
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.
My cryptic version...
a = ['123', '456'][b == True]
1 Comment
jdi
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" See PEP 308 for more info.
2 Comments
clickbait
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
JeanCarlos Chavarria
This is not an elaborative answer, I dont see it helpful