Home  >  Article  >  Backend Development  >  Detailed explanation of python ternary operator

Detailed explanation of python ternary operator

高洛峰
高洛峰Original
2016-10-19 13:23:431508browse

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 errors, but the article also mentioned that when V1="", there will be problems
For example,

print (True and '') or 'V'
print (False and '') or 'V'

The output is always: V

The perfect solution is mentioned in "Python Core Programming":

V1 if :Y), or ternary operator. (C is a conditional expression; function, because he believed that the code should be kept simple so that programmers would not make mistakes easily. However, after more than ten years, he gave up, mainly because people tried to simulate it using and and or, but most of them were 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 does not agree with this syntax. (You can take a look at PEP 308, which

There are different solutions in .) People expressed great demands for this problem in Python.

Guido van Rossum finally chose the most promising (and his favorite) solution, and then put It is used in some modules in the standard library. According to the PEP, "This review examines a large number of real-world cases, including different applications, and code completed by different programmers." The final syntax for Python 2.5 integration was determined as: X if C else Y .


As mentioned above, this syntax was only added in python2.5, but since 2.4 and previous versions are not usually used, it is enough~



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn