This article shares a detailed introduction to the ternary operator in Python
python does not have a ternary descriptor, but it can be implemented through simulation.
One of them is:
(X and V1) or V2
Normally there will be no error, but the article also mentioned that when V1="" , there will be problems
such as
print (True and '') or 'V'
print (False and '') or 'V'
The output is always: V
The perfect solution is mentioned in "Python Core Programming":
The original text is as follows:
If you come from the C/C++ or Java world, then it is difficult for you to ignore the fact that Python has been used for a long time
There is no conditional expression(C ? X : Y), or ternary operation operator. (C is a conditional expression; Y is the result when C is False) Guido van Rossum has always refused to add such a feature because he believes that the code should be kept simple so that programmers are less likely to make mistakes. However, more than ten years later, He gave up, mainly because people tried to simulate it using
and and or, but mostly got it wrong. According to the FAQ, the correct way (and not the only one) is
(C and [X] or [ Y])[0] . The only problem is that the community doesn't agree with this syntax. (You can take a look at PEP 308, which
has a different approach.) People have expressed a lot of opinions about this problem in Python
Guido van Rossum finally chose the most promising (and his favorite) solution, and then applied it to some modules in the standard library. According to the PEP, "This The review examined a large number of real-world cases, including different applications, and code completed by different
programmers." Finally, the syntax of Python 2.5 integration was determined to be: X if C else Y .
As above As mentioned, this syntax was only added in Python 2.5, but since 2.4 and previous versions are not usually used, it is enough~
The above is the detailed content of Detailed introduction to python ternary operator. For more information, please follow other related articles on the PHP Chinese website!