Python-equivalent of short-form "if" in C++

C++PythonSyntax

C++ Problem Overview


> Possible Duplicate:
> Python Ternary Operator

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

C++ Solutions


Solution 1 - C++

a = '123' if b else '456'

Solution 2 - C++

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

Solution 3 - C++

My cryptic version...

a = ['123', '456'][b == True]

Solution 4 - C++

See PEP 308 for more info.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhuyView Question on Stackoverflow
Solution 1 - C++SilentGhostView Answer on Stackoverflow
Solution 2 - C++jdiView Answer on Stackoverflow
Solution 3 - C++SocramView Answer on Stackoverflow
Solution 4 - C++ghostdog74View Answer on Stackoverflow