Does Python have a ternary conditional operator?

2018-12-30 22:26发布

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

25条回答
看淡一切
2楼-- · 2018-12-30 23:16

Yes, you can use it that way :

is_fat = True
state = "fat" if is_fat else "not fat"

Read more about ternary conditional operator

查看更多
骚的不知所云
3楼-- · 2018-12-30 23:16

Yes:

Let’s say you want to give variable x some value if some bool is true and likewise

X = 5 if something else x = 10

X = [some value] if [if this is true first value evaluates] else [other value evaluates]

查看更多
还给你的自由
4楼-- · 2018-12-30 23:17

expression1 if condition else expression2

>>> a = 1
>>> b = 2
>>> 1 if a > b else -1 
-1
>>> 1 if a > b else -1 if a < b else 0
-1
查看更多
牵手、夕阳
5楼-- · 2018-12-30 23:18

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:

  • The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic 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:

查看更多
冷夜・残月
6楼-- · 2018-12-30 23:18

An operator for a conditional expression in Python was added in 2006 as part of Python Enhancement Proposal 308. Its form differ from common ?: operator and it's:

<expression1> if <condition> else <expression2>

which is equivalent to:

if <condition>: <expression1> else: <expression2>

Here is an example:

result = x if a > b else y

Another syntax which can be used (compatible with versions before 2.5):

result = (lambda:y, lambda:x)[a > b]()

where operands are lazily evaluated.

Another way is by indexing a tuple (which isn't consistent with the conditional operator of most other languages):

result = (y, x)[a > b]

or explicitly constructed dictionary:

result = {True: x, False: y}[a > b]

Another (less reliable), but simpler method is to use and and or operators:

result = (a > b) and x or y

however this won't work if x would be False.

A possible workaround is to make x and y lists or tuples as in the following:

result = ((a > b) and [x] or [y])[0]

or:

result = ((a > b) and (x,) or (y,))[0]

If you're working with dictionaries, instead of using a ternary conditional, you can take advantage of get(key, default), for example:

shell = os.environ.get('SHELL', "/bin/sh")

Source: ?: in Python at Wikipedia

查看更多
余生无你
7楼-- · 2018-12-30 23:21

From the documentation:

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

New since version 2.5.

查看更多
登录 后发表回答