python (bool) ? then : else syntax?

Possible Duplicate:
Python Ternary Operator

In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression.

For example,

return (i < x) ? i : x

This will return i if i < x, otherwise it will return x. I like this because it is much more compact in many cases than the longer syntax which follows.

if (i < x)
  return i
else
  return x

Is it possible to use this syntax in python and if so, how?


You can use (x if cond else y) , eg

>>> x = 0
>>> y = 1
>>> print("a" if x < y else "b")
a

That will work will lambda function too.


Yes, it looks like this:

return i if i < x else x

It's called the conditional operator in python.


Ternary operator in python.

a if b else c

>>> a=1
>>> b=2
>>> a if a<b else b
1
>>> a if a>b else b
2
链接地址: http://www.djcxy.com/p/7398.html

上一篇: python:iif或(x?a:b)

下一篇: 蟒蛇(布尔)? 那么:else语法?