Introduction to the use of ternary operators in Python language techniques

Source: Internet
Author: User
Python does not support ternary operators in C + +? :, the alternative method is ... if ... else ...
For example, use the following syntax to achieve the minimum value of three numbers.
ND1 if nD1 < (nD2 if nD2

The correct method for Python ternary operators

Because the next week to write the project in PHP, so the weekend at home re-read PHP syntax, see ternary descriptors, suddenly remembered that Python is no ternary descriptor, the impression vaguely remember that there is a simulation of the implementation, so on the internet search.
(corresponding to the C language X?) V1:V2)

One of these is:

(X and V1) or V2

Normally there is no mistake, but the article also mentions that when v1= "", there will be problems
Like what

Copy the Code code as follows:


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 X else V2

The original text reads as follows:

If you're from a C + + or a Java world, it's hard to ignore the fact that Python is a long
There is no conditional expression in a period of time (C? X:Y), or ternary operator. (C is the conditional expression; X is when C is true
result, Y is the result when C is False) Fan Rossam has been refusing to join such a feature because he believes that it should be
Keeping the code simple makes it easy for programmers to make mistakes. But after more than 10 years, he gave up, mostly because people tried to use
And and or to emulate it, but most of them are wrong. According to the FAQ, the correct method (not the only one) is
(C and [X] or [Y]) [0]. The only problem is that the community does not agree with such a grammar. (You can take a look at PEP 308, which
There are different scenarios in the.) There is a great demand for Python's question.
The Fan Rossam finally chose the one that was most favored (and his favorite) and applied it to the standard library.
Some of the modules. According to PEP, "This review examines a large number of real-world cases, including different applications, and by different
The code that the programmer completes. "The final syntax for Python 2.5 is determined as: X if C else Y.

As mentioned above, this grammar is added in python2.5, but because it will not be used in the 2.4 and the previous version, so it is enough ~

Most high-level languages now support "?" The ternary operator (ternary operator), which corresponds to the following expression: condition? Value if True:value if False. Strangely enough, such a common operator Python doesn't support it! Admittedly, we can express through the If-else statement, but the original line of code can be done more than the line, obviously not concise. It doesn't matter, in Python there is actually a corresponding way of expression.

As an example: char *ret = (x!=0)? "True": "false" the line of code that corresponds to the python form is ret = (x and "True") or "false" (very simple, in fact the parentheses can be removed). At run time, the Python virtual opportunity evaluates to the Boolean expression on the right side of the assignment (note that this is not a ternary expression), and the return value is the last value to be parsed. Why is "last parsed" rather than "last" in an expression? Because a Boolean expression has a short-circuit effect, such as a or B, if a is true then the B is not analyzed. Well, I guess it's almost clear how the Python code works. If x is true, because the string "true" is also true, then return "true", conversely, X is false, then there is no need to see the string "true" (short-circuit effect), directly return "False".

It is not difficult to see that ternary operations in Python can in fact be expressed by borrowing Boolean evaluation. Then, sometimes there is a slight problem. For example, char *ret = x? "" or "VAL". According to the previous example, it is natural to think of this in Python, ret = x and "" or "VAL". Wrong! Whether the boolean evaluation of x is TRUE or FALSE, Ret gets always "VAL". Is that weird? Not surprisingly, because the boolean evaluation of an empty string in Python is false, so that X and "" are always false, so the nature of RET gets is always "VAL". There are two ways to solve this problem, the first, and one of my favorites, is to write RET = not x and "VAL" or "". Second, trouble a little ret=x and [""] or ["VAL"], and then each fetch ret[0] as the return value, this is because [""] in the Boolean evaluation value is true.

Discussion one: The first method of code is clearly concise, high efficiency, then it is necessary to use the second kind? Of course, the first approach has limitations and can only be used if we are very certain that the boolean evaluation of one of the values cannot be false. In our example, it is possible to use because "VAL" definitely returns true. If it is a two variable, like this ret=x and Val1 or val2, you can only honestly write ret=x and [val1] or [Val2], and then take ret[0] as a result. Because this line of statement does not express "when X is true returns VAL1, otherwise returns VAL2", instead "returns VAL2 if X is true and Val1 returns to true Val2".

Discussion two: We all know that Python has a list and a tuple, the preceding line of code ret=x and [""] or ["VAL"] we are solved by the list, some people may prefer a tuple, so it will be written ret=x and ("") or ("Val"). Wrong! Here Ret[0] is always an empty string (tested on 2.5). This is one of my more faint, why [""] is True and ("") is false?

Finally, we enclose Python's Boolean evaluation results for typical values, which is useful for us to write an equivalent statement of ternary operations.


Input Boolean evaluation
1 , -1 , [""] True
0, "", None, [], (), {}, ("") False
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.