141

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

2

4 Answers 4

256
a = '123' if b else '456'
Sign up to request clarification or add additional context in comments.

3 Comments

This ternary operator was introduced in Python 2.5.
For future reference, here's the Python documentation for the conditional expression: docs.python.org/reference/expressions.html#boolean-operations
What does that mean?
26

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

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.
21

My cryptic version...

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

1 Comment

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"
-1

See PEP 308 for more info.

2 Comments

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.
This is not an elaborative answer, I dont see it helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.