Foreword
In java, there are similar (condition) a:? The syntax b, said that if the condition is true, returns a, on the contrary returns b. We call this the ternary operator.
That Python, there is no such syntax, it was very unfortunately, no!
Ternary operator in Python
But, in Python, although there is no such expression syntax, but by means if -- else
may be implemented similar to the effect of the ternary operator. Examples are as follows:
The a, b two numbers, if a> b Returns 'more', otherwise, returns 'less' we can represent in Python
if a > b: return 'more' else: return 'less'
The above code generally conventional practice but, in fact, also be used as such, the following example: if--else
>>> a,b = 1,2 >>> c = 'more' if a>b else 'less' >>> print(c) less
The example above only the amount c = 'more' if a>b else 'less'
on four lines of code to achieve the functions of conventional practice in.
Further, there is another method in Python can achieve the effect of the ternary operator as follows:
>>> c = {True:'more',False:'less'}[a>b] >>> c 'less'
No more exchanges of public attention: Ape school desk