Does Python have a ternary conditional operator?
如果Python没有三元条件运算符,是否有可能使用其他语言构造来模拟一个条件运算符?
 Yes, it was added in version 2.5.  
 The syntax is:  
a if condition else b
 First condition is evaluated, then either a or b is returned based on the Boolean value of condition  
 If condition evaluates to True a is returned, else b is returned.  
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
 Note that conditionals are an expression, not a statement.  This means you can't use assignments or pass or other statements in a conditional:  
>>> pass if False else x = 3
  File "<stdin>", line 1
    pass if False else x = 3
          ^
SyntaxError: invalid syntax
 In such a case, you have to use a normal if statement instead of a conditional.  
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
 If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean.  For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9 .  
Official documentation:
You can index into a tuple:
(falseValue, trueValue)[test]
 test needs to return True or False.  
 It might be safer to always implement it as:  
(falseValue, trueValue)[test == True]
 or you can use the built-in bool() to assure a Boolean value:  
(falseValue, trueValue)[bool(<expression>)]
For versions prior to 2.5, there's the trick:
[expression] and [on_true] or [on_false]
 It can give wrong results when on_true has a false boolean value.1  
 Although it does have the benefit of evaluating expressions left to right, which is clearer in my opinion.  
1. Is there an equivalent of C's ”?:” ternary operator?
链接地址: http://www.djcxy.com/p/106.html上一篇: 为什么(>>)没有定义为(*>)?
下一篇: Python是否有三元条件运算符?
