If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
转载于:https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
转载于:https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator
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: