Possible Duplicate:
Python Ternary Operator
Is there a way to write this C/C++ code in Python? a = (b == true ? "123" : "456" )
Python's short-hand method for writing an if/else statement There are three components to the ternary operator: the expression/condition, the positive value, and the negative value. When the expression evaluates to true, the positive value is used—otherwise the negative value is used.
Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.
a = '123' if b else '456'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With